views:

148

answers:

3

If a TCP socket server listens on port 28081 for incoming connections and then accepts a connection and start receiving data. Is the port that data is coming into still 28081 or does the port get changed.

for example what port does the incoming data come to in the pseudo code below? Is it still 28081 or does the OS assign a new port?:

bind
listen (on port 28081)

while 1
  fd = accept
  fork
  if child process incoming data 
+2  A: 

Yes, it stays on that port, though some protocols (FTP) might open a second connection on another port. Dont think of a port as a physical path or plug, like a USB port that can only have one thing plugged into it. But rather think of it as an identifier for the service being requested.

Often, though, the new socket connection is passed off to another thread which handles the read/writes for that specific connection.

GrandmasterB
+8  A: 

A TCP connection is uniquely identified by a two (IP address, TCP port) tuples (one for each endpoint). So by definition, one can't move a port or IP address of a connection but just open a different one.

If the server binds to port 28081 all accepted connections will have this port on the server side (although they most likely will have varying port numbers on the client side).

For example, if two processes from the same client machine will connect to the same server, the IP address and TCP port on the server side will be the same for both connections. On the client side however, they will have two different port numbers allowing the operating system on both sides to uniquely identify which process and file descriptor the received TCP packets should be assigned to.

Andre Holzner
@Andre - who handles the port designation on the client? Does the OS layer recognize an exact match on an existing connection and dynamically map the new connection to a new port?
Jess
Jess,I'm not sure I fully understand the question. When the client opens a new connection to the server's port 28081, it makes sure it uses a source port address it hasn't used yet for the same server host and port. I.e. if you have a connection of client source port 40'000 to the server port 28081, the next connection could use source port 40'001 to the same server on port 28081. This ensures that both the client and the server know that this is a new connection because at least one of the four quantities `(client IP address, client TCP port, server IP address, server TCP port)` is different.
Andre Holzner
+1  A: 

There can be more than one client connecting to one port, as the connection is identified by both the server and client IP address and port. So, accepting the connection from one client does not block others from connecting. You could even connect another time from the same client (using another client port).

Frank