Do TCP clients' ports and TCP servers' ports share the same address space?

conflict, networking, port-number, sockets, tcp

Solution

The answer is "it depends" (on OS and socket options).

On Linux with `SO_REUSEADDR` on both sockets, the exact situation described is possible:

$ sudo netstat -panl |grep 12300
tcp        0      0 127.0.0.1:12300         0.0.0.0:*               LISTEN      3591/nc         
tcp        0      0 127.0.0.1:12300         127.0.0.1:25            ESTABLISHED 3547/nc         
tcp        0      0 127.0.0.1:25            127.0.0.1:12300         ESTABLISHED 3548/exim4

...but only when the client gets there first. When the server is already listening, the same port can't be bound by client (and won't ever be automatically assigned to client, IIRC).

On Windows, with or without `SO_REUSEADDR`, port is port and `bind` fails (be it the server or the client who did it first).

Problem

On the same machine, if a tcp client has occupied port 12345, for example, the client has connected to google.com, and then a tcp server tries to bind its listening port on 12345, is this allowed?

Original source