Does ServerSocket accept return socket on arbitrary port?

后端 未结 2 636
慢半拍i
慢半拍i 2020-11-28 10:44

I\'ve seen many answers similar to this one in regards to serversockets in java: \"Let\'s say you have a server with a serversocket on port 5000. Client A and Client B will

2条回答
  •  南笙
    南笙 (楼主)
    2020-11-28 11:26

    The Server then opens up its own next available port, and sends that to the client.

    No. It creates a new socket with the same local port number. No second port number is allocated or sent to the client. The SYN/ACK segment which is the server's response to the connect request does not contain a second port number.

    Here, Client A connects to the new port,

    No. The client acknowledges the SYN/ACK packet and the client is connected to the original port from then on, after acknowledging the SYN/ACK. There is no second connect.

    and the server now has port 5000 available again."

    It always did.

    I've seen answers like this in multiple questions on stackoverflow about how a different port is used in the returned socket of the accept() than the port that the ServerSocket is listening on.

    Any such answer is incorrect and should be downvoted 'with extreme prejudice' and commented on adversely. The TCP handshake is defined in RFC 793 and does not specify allocation and exchange of a second port and a second connect message. There are only three messages, which isn't even enough for that to occur.

    So why would the accept() need to return a socket bound to a different port?

    It doesn't.

    Doesn't the quartet of information sent in every header distinguish multiple connections to the same server port from different machines enough where it would not need to use different ports on the server machine for communication?

    Yes.

提交回复
热议问题