• C

Winsock Help!!!

bradleyb1537Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

bradleyb1537Author Commented:
Im trying to figure out the problem in my code I beleive from everything ive read that this shoudl work but when i run the program as a server then as a client the server does not display the correct information the code is posted below:

//Link with Wsock32.lib
#include <iostream.h>
#include <stdio.h>
#include <winsock2.h>

SOCKET SockIn,SockOut;
char buff[100];
char debarray[1000];
void DebugIt(char *info)
{
    FILE *fp=fopen("debugs.txt","a+");
      fprintf(fp,"%s",info);
      fclose(fp);
}

void DebugInit()
{
    FILE *fp=fopen("debugs.txt","w");
      fclose(fp);
}


int StartServer(SOCKET sock, int port)
{    
   WSADATA w;
   SOCKET come;
 

      if(WSAStartup(MAKEWORD(2,2),&w)!=0) {
            cout << "\nWSAStartup Error!";
            return 0;
      }
   come = socket(AF_INET,SOCK_STREAM,0);
   sockaddr_in addr; //the address structure for a TCP socket

   addr.sin_family = AF_INET; //Address family internet
   addr.sin_port = 50; //Receiving port
   addr.sin_addr.s_addr = inet_addr("127.0.0.1"); //htonl(INADDR_ANY);

   if(bind(come,(SOCKADDR *)(&addr),sizeof(addr))==SOCKET_ERROR)
   {
         cout << "Bind failed.\n";
         return 0;
   }

   if(listen(come,3)==SOCKET_ERROR)
   {
         cout << "Listen failed.\n";
         return 0;
   }
   sock = accept(come,NULL,NULL);
   if(sock==SOCKET_ERROR) {
         cout << "Accept Error\n";
         return 0;    
   }
   return 1;
}

int StartClient(SOCKET SockOut, int port, char *ip)
{
WSADATA w;
      if(WSAStartup(MAKEWORD(2,2),&w)!=0) {
            cout << "\nWSAStartup Error!";
            return 0;
      }
   sockaddr_in target;
SockOut=socket(AF_INET,SOCK_STREAM,0);
   target.sin_family = AF_INET;
   target.sin_port = 50; //SERVER listening port
   target.sin_addr.s_addr = inet_addr("127.0.0.1"); //inet_addr(ip);

DebugIt("Can't connect! Aborting!\n");
   if(connect(SockOut,(LPSOCKADDR)&target,sizeof(target)) !=0)
   {
         cout << "Connect failed.\n";
      WSACleanup();
      exit(0);
   }

   strcpy(buff,"This is a TEST!!!");
   send(SockOut,buff,sizeof(buff),0);

   strcpy(buff,"000");
   send(SockOut,buff,sizeof(buff),0);
      return 1;
}

void Client()
{
      while(buff[0] != '0' || buff[1] != '0' || buff[2] != '0')
      {
      cout << "\nInput: ";
      //cin >> buff;
      cin.getline(buff,100,'\n');
      send(SockOut,buff,sizeof(buff),0);
      }
}

void Server()
{
      int RetVal=SOCKET_ERROR;
      cout << "In Server!";
      DebugIt("\nIn Server()");
         //while(buff[0] != '0' || buff[1] != '0' || buff[2] != '0')
          //while(RetVal==SOCKET_ERROR && (buff[0] != '0' || buff[1] != '0' || buff[2] != '0'))
            //{
            RetVal=recv(SockIn,buff,sizeof(buff),0);
                  if((RetVal==0) || (RetVal==WSAECONNRESET) )//|| (RetVal==WSAECONNABORT))
                  {
                        cout << "Connection closed on other end!\n";
                        return;
                  }
            //if(buff[0] == 'c' || buff[1] == 'm' || buff[2] == 'd')
                  //{
                        cout << buff;
                        DebugIt(buff);
                  //}

      //}//End of while 000 was entered

                              cout << buff;
                        DebugIt(buff);
      DebugIt("\nDone Server()");
      cout << "\nDone Server()";

}

int main()
{
      int i;
      DebugInit();
      cout << "\n1: Server\n2: Client\n";
      cin >> i;
      if(i==1)
            if(StartServer(SockIn,9110)) {
                  cout << "\nStarted fine";
                  Server();
            }
            else
                  cout << "\nERROR!!\n";
      if(i==2)
            if(StartClient(SockOut,9110,"127.0.0.1")) {
                  cout << "\nClient Working";
                  //Client();
            }
            else
                  cout << "\nERROR!!\n";
      closesocket(SockIn); closesocket(SockOut);
      WSACleanup();
      //exit(0);
      return 0;

}
 
0
TascoDLXCommented:
StartServer() needs to pass its SOCKET by reference:

  int StartServer(SOCKET &sock, int port)
   
After you finish sending your data in StartClient(), call shutdown():

  strcpy(buff,"This is a TEST!!!");
  send(SockOut,buff,sizeof(buff),0);

  strcpy(buff,"000");
  send(SockOut,buff,sizeof(buff),0);

  shutdown(SockOut, 1);
  return 1;

Your Server() function was a mess.  Here it is simplified:

  void Server()
  {
     int RetVal;
     cout << "In Server!";
     DebugIt("\nIn Server()\n");

     while ((RetVal=recv(SockIn,buff,sizeof(buff),0)) != 0)
     {
        if (RetVal==SOCKET_ERROR)
        {
           cout << "Connection closed with " << WSAGetLastError() << "\n";
           return;
        }

        cout << buff;
        DebugIt(buff);
     }

     DebugIt("\nDone Server()");
     cout << "\nDone Server()";
  }

Enjoy!
0
mrwad99Commented:
Yep, just bet me to it TascoDLX !

Also bradleyb1537,

I find it is always useful to split up into separate client and server files; this makes it much more clear when it comes to debugging and also when it comes to other people maintaining your code.
0
Managing Security Policy in a Changing Environment

The enterprise network environment is evolving rapidly as companies extend their physical data centers to embrace cloud computing and software-defined networking. This new reality means that the challenge of managing the security policy is much more dynamic and complex.

bradleyb1537Author Commented:
I rewrote my code with your suggestion of passing by reference and I still get an invalid socket return from my recv and it fails to the message. My new code is as follows:
//link with wsock32.lib

#include <iostream.h>
#include <stdio.h>
#include <winsock.h>

#define PORT 50

SOCKET sock;
char buff[1024];

void Server();
void Client();

int StartServer(SOCKET &sock, short port)
{
     gethostname(buff,sizeof(buff));
     cout << "\nServer on computer: " << buff << " Port:" << port;

     sock=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
     if(sock==INVALID_SOCKET)
     {
          cout << "\nInvalid Socket";
          return 0;
     }

     SOCKADDR_IN addr;
     addr.sin_family=AF_INET;
     addr.sin_addr.s_addr=INADDR_ANY;
     addr.sin_port=htons(port);

     cout << "\nBinding.";
     if(bind(sock,(LPSOCKADDR)&addr,sizeof(addr))==SOCKET_ERROR)
     {
          cout << "\nBind error!";
          return 0;
     }
     cout << "\nListening.";
     if(listen(sock,SOMAXCONN)==SOCKET_ERROR)
     {
          cout << "\nError Listening.";
          return 0;
     }

     SOCKET remoteSock;

     remoteSock=accept(sock,NULL,NULL);
     if(remoteSock==INVALID_SOCKET)
     {
          cout << "\nError Accepting.";
          return 0;
     }

   return 1;
}

int StartClient(SOCKET &sock, short port, char *ip, char *hostname)
{
     sock=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
     if(sock==INVALID_SOCKET)
     {
          cout << "\nInvalid Socket";
          return 0;
     }

     SOCKADDR_IN addr;
     addr.sin_family=AF_INET;
     addr.sin_port=htons(port);
     if(hostname==NULL)
          addr.sin_addr.s_addr=inet_addr(ip);
     else
     {
          LPHOSTENT lpHostEntry;
          lpHostEntry=gethostbyname(hostname);
          if(lpHostEntry==NULL)
          {
          cout << "\nInvalid Hostname";
          return 0;
          }
          addr.sin_addr=*((LPIN_ADDR)*lpHostEntry->h_addr_list);
     }

     cout << "\nConnect().";
     if(connect(sock,(LPSOCKADDR)&addr,sizeof(addr))==SOCKET_ERROR) {
          cout << "\nConnect Error.";
          return 0;
     }

     return 1;
}


int main()
{
     WORD VersionRequest=MAKEWORD(1,1);
     WSADATA WSAData;
     int i;


     WSAStartup(VersionRequest, &WSAData);
     gethostname(buff,sizeof(buff));
     cout << "\nComputer name: " << buff;

     cout << "\n\nChoose your connection:\n1: Server\n2: Client(connect with ip)\n3: Client(connect with hostname)\n";
     cin >> i;
     if(i==1)
          if(StartServer(sock,PORT)) {
               cout << "\nStarted fine";
               Server();
          }

     if(i==2) {
               cout << "\nIP Adress:";
               cin >> buff;
               StartClient(sock,PORT,buff,NULL);
               Client();
          }

     if(i==3)
          {
               cout << "\nHost name:";
               cin >> buff;
               StartClient(sock,PORT,NULL,buff);
               Client();
          }
     closesocket(sock);
     WSACleanup();
     return 0;

}

void Client()
{
     int RetVal;
     sprintf(buff,"Hello from client!");
     RetVal=send(sock,buff,sizeof(buff)-1,0);
     if(RetVal==INVALID_SOCKET)
     {
          cout << "\nError Sending.";
     }
     shutdown(sock,1);
}

void Server()
{
     int RetVal;
     cout << "\nIn Server!";

     RetVal=recv(sock,buff,sizeof(buff)-1,0);
     if(RetVal==INVALID_SOCKET)     cout << "\nError Receiving.";

     cout << "\nRecieved: " << buff;
     cout << "\nDone Server()";

}
0
TascoDLXCommented:
You swapped variables on me.  In StartServer(), the SOCKET you want your reference to return is the one returned by accept().

Add sock=remoteSock to the end of StartServer() and it should work:

  SOCKET remoteSock;
  remoteSock=accept(sock,NULL,NULL);
  if(remoteSock==INVALID_SOCKET)
  {
    cout << "\nError Accepting.";
    return 0;
  }
  sock=remoteSock;
  return 1;

Although you'll probably want to change sock to a local variable and make remoteSock your reference instead.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
bradleyb1537Author Commented:
Great !! thanx for all the help hope these points are enough
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.