Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

Winsock Help!!!

Posted on 2003-03-17
6
Medium Priority
?
244 Views
Last Modified: 2010-04-15
0
Comment
Question by:bradleyb1537
  • 3
  • 2
6 Comments
 

Author Comment

by:bradleyb1537
ID: 8156340
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
 
LVL 3

Expert Comment

by:TascoDLX
ID: 8158065
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
 
LVL 19

Expert Comment

by:mrwad99
ID: 8158084
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
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 

Author Comment

by:bradleyb1537
ID: 8162631
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
 
LVL 3

Accepted Solution

by:
TascoDLX earned 360 total points
ID: 8162982
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
 

Author Comment

by:bradleyb1537
ID: 8163823
Great !! thanx for all the help hope these points are enough
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Preface I don't like visual development tools that are supposed to write a program for me. Even if it is Xcode and I can use Interface Builder. Yes, it is a perfect tool and has helped me a lot, mainly, in the beginning, when my programs were small…
Summary: This tutorial covers some basics of pointer, pointer arithmetic and function pointer. What is a pointer: A pointer is a variable which holds an address. This address might be address of another variable/address of devices/address of fu…
The goal of this video is to provide viewers with basic examples to understand recursion in the C programming language.
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use nested-loops in the C programming language.
Suggested Courses

577 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question