Do TCP connections get moved to another port after they are opened?

19,337

Solution 1

A TCP connection is uniquely identified by 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.

Solution 2

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.

Solution 3

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).

Share:
19,337
Ivan Novick
Author by

Ivan Novick

Updated on June 03, 2022

Comments

  • Ivan Novick
    Ivan Novick almost 2 years

    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