Do TCP connections get moved to another port after

2019-01-13 04:36发布

This question already has an answer here:

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 

3条回答
趁早两清
2楼-- · 2019-01-13 05:09

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.

查看更多
放荡不羁爱自由
3楼-- · 2019-01-13 05:20

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

查看更多
冷血范
4楼-- · 2019-01-13 05:28

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.

查看更多
登录 后发表回答