Click to See Complete Forum and Search --> : Socket programming


irishabh
February 8th, 2008, 07:05 PM
Hi,

I am trying to establish a simple server and a client. Server is bound to port (4731), using the following code:
-----------------
CSocket servsocket;
ipaddr.Format("128.195.52.110");
listenport = 4731;

if(servsocket.Create(listenport,SOCK_STREAM,ipaddr) == 0){

msg.Format("Error: %d",GetLastError());
MessageBox(msg);
}
-----------------

The socket gets created (as I don't get the error message.

Now, on client side (at a different machine with a different IP address), a similar code is run to bind the client socket to port 4730. Socket creation is successful here too. Then it sends a Connect() request to the server on port 4371.

Server is listening to port 4371 using command 'servsocket.Listen(5);' within a while(1) loop. When it tries to accept the connect request from client (using servsocket.Accept((CAsyncSocket &) sock,&saddr,&socklen)), and I check the IP address and port of the client in saddr variable, it does not show client's IP address.

Can someone please tell me where I might have made a mistake?

I have the following doubt:
Should the client send Connect request on the port on which server is bound to and listening?

Please help.
Regards,
Ish

Orum
February 11th, 2008, 06:06 PM
I'm not familiar with MFC, so I can't help with the code itself. However, there are some general guidelines when using TCP connections that you should follow:

- You should rarely, if ever, bind a client to a IP address and port. Binding should be done only on sockets being placed in a listen state. If you are going to connect, a source port will be chosen automatically (dynamically) for the socket.

- Yes, clients should connect to the port that the server is listening on. However, the port the client is receiving on, as mentioned in the previous note, need not be the same port as the server for TCP connections (UDP is somewhat more complex and protocol specific).

- You may want to look at the Winsock FAQ (http://tangentsoft.net/wskfaq/) for examples of simple client/server connections. I don't believe it has MFC code, however.