问题原文
原帖链接 · doc_id · CC BY-SA 4.0
My understanding of TCP connection is that a source PORT remains exclusive to one connection, no matter the destination is, so the number of connections from local port 12345 for example can never exceed 1.
I recently read that a TCP connection is identified by <src IP, src PORT, dst IP, dst PORT>
TCP allows source port sharing across multiple processes, but each process requires a free port to bind to for its connection
so I went to validate that "port sharing across processes": this must mean that the same source port can be used to connect to different destinations.
However, when experimenting this, I tried these two commands:
nc -v -p 12345 google.com 80
which works well (-v for verbose, and -p to specify the source port as 12345, for my learning purpose)
Now, simultaneously running this command on a different shell
nc -v -p 12345 github.com 80
fails with this error message:
nc: connectx to github.com port 80 (tcp) failed: Address already in use
the reason I specified the same source port with -p is to validate that a source port can be shared. There's no need for this practically, in real-world scenario I would not even worry about source port. According to this, is it true that a source port will be only used once?
已采纳解答
原帖链接 · nneonneo · CC BY-SA 4.0
There is no reason why two processes cannot use the same source port, as long as they do not both connect to the same destination (host, port). On many UNIX systems, set the SO_REUSEPORT option to enable processes to share a port number; on Windows, set SO_REUSEADDR. For example, with socat:
- process 1:
socat stdio tcp:google.com:80,bind=:12345,reuseport - process 2:
socat stdio tcp:bing.com:80,bind=:12345,reuseport
These two processes can run simultaneously, and will both have source port 12345 (as you can confirm with netstat).
Note, however, that you will almost certainly run into issues if the sockets are not closed cleanly on both ends, as unclosed TCP sockets will enter a TIME_WAIT state which will cause the four-tuple (srcaddr, srcport, dstaddr, dstport) to be tied up until the wait period expires. Therefore, when using a single source port for multiple connections, you cannot reconnect to the exact same server & port unless the previous connection has fully shut down or the TIME_WAIT period has expired.
摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。
