Pergunta

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?

Foi útil?

Solução

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

Outras dicas

No. Port is port.

THAT SAID: Clashes rarely are there because normally servers start before the client ask for a non specified port (i.e. the client never sets a port number, his machine takes a free one).

And there are predefined ports for most servers.

http://www.webopedia.com/quick_ref/portnumbers.asp http://www.ietf.org/rfc/rfc1700.txt?number=1700

And ranges:

http://www.tcpipguide.com/free/t_TCPIPApplicationAssignmentsandServerPortNumberRang-2.htm

As you can see, registerd ports go to 49151 and from there they are reserved for dynamic use. So, client ports normally come from that range 49152 upward which services should not use.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top