tags:

views:

51

answers:

1

Let's say I have a server socket listening on port no 5010. When client tries to connect to this server socket using connect() API, server accepts socket connection in accept() API.

accept() API returns a new socket for server/client connection. Now all data transfer between server and client is done using this newly created socket. Does the data transfer happens on same port 5010. If not, how the ports are chosen when new socket is returned as a result of accept() API ?

A: 

The connection between the server and the client socket is identified by the tuple (serverAddress, serverPort, clientAddress, clientPort). The server address and server port always stay the same (obviously). The client allocates a (semi-)random "source" port to avoid collisions even if re-using the same address (e.g. when there are multiple clients on the same machine).

David Schmitt
Does it mean that if there are five clients connected to the server, each client is sending data to port 5010 only. How a server can differentiate from which client data is coming ?
cppdev
By the second part of that tuple (client ip, client port).
Nikolai N Fetissov