Search code examples
socketstcpnetwork-programmingport

Can a given destination port be associated with more than one TCP connection?


After doing some search for this, I got to know a few points

  1. We cannot multiplex a port for TCP.
  2. If two connections use the same protocol and have the same destination ports, they must have the same connection.
  3. I am quite confused about how some sites say that TCP can only have one application listening on the same port at one time while others say multiple listening TCP sockets, all bound to the same port, can co-exist, provided they are all bound to different local IP addresses.

Reading the above stuff has left me more confused than ever. Can a destination port be associated with more than one TCP connection?


Solution

  • We cannot multiplex a port for TCP.

    This is wrong. You can run multiple TCP connections on the same port, as long as they are unique connections. And it is not very difficult to write code that multiplexes I/O on multiple TCP sockets within the same process.

    If two connections use the same protocol and have the same destination ports, they must have the same connection.

    This is wrong. A TCP connection is uniquely identified by a combination of protocol + local IP/port + and remote IP/port.

    Two connections that use the same protocol and same destination IP/port are still unique if they use different source IP/port to connect from. For instance, multiple clients running on the same machine can connect to the same server if they use a different local port to connect from. Which is typically the case, as most clients use a random available local port, selected by the OS, for the outbound connection.

    Likewise, two connections that use the same protocol and the same source IP/port are still unique if they connect to different destination IP/port. For instance, multiple clients running on the same machine can use the same local IP/port to connect from if they connect to different servers.

    some sites say that TCP can only have one application listening on the same port at one time

    This is correct, but only if all of the listeners are trying to use the same local IP/port at the same time. Only 1 listener is allowed on it.

    others say multiple listening TCP sockets, all bound to the same port, can co-exist, provided they are all bound to different local IP addresses.

    This is correct.

    Can a destination port be associated with more than one TCP connection?

    Yes. Even if there is only 1 listener on that port, every connection it accepts will be using that same local port on the server side, but a different source IP/port from the client side. This allows multiple clients from different remote machines to connect to the same server at the same time.