Harry
Harry

Reputation: 3927

Behavior of accept() and TCP packet delivery

Java documentation says that a ServerSocket, x, that is listening on, say, port 5555 returns a new Socket, y, from its accept() method such that:

  1. the local port of y is set to 5555; and

  2. x continues to listen on port 5555 to accept() new connections.

I have verified that the above is indeed the case.

However, this wikipedia entry on Port has this to say:

This process is known as listening and involves the receipt of a request on the well-known port and reestablishing one-to-one server-client communications on another private port, so that other clients may also contact the well-known service port.

To me, the above wikipedia excerpt tends to make more sense... since from what I've read and understood about TCP/IP,

  1. the destination IP address helps deliver the packet to the right host; and

  2. the destination port helps deliver the packet to the right process on the destination host

Thus, the given the documentation and behavior of accept() in Java, I'm wondering how could packet delivery be possibly achieved in case of a multithreaded client attempting to talk to a multithreaded server (by opening two communication channels, one in each thread)? In such a case, how would Java (or, the underlying TCP/IP stack) know which packet belongs to which channel when all packets would have the same destination IP address and port values set?

EDIT: Please see EJP's response and also Nikolai's comment below. According to them, the above wikipedia claim was wrong. EJP went ahead and fixed the wikipedia entry.

Upvotes: 3

Views: 371

Answers (2)

user207421
user207421

Reputation: 310840

The Wikipedia article is wrong. Was wrong: I fixed it. Take another look now. The accepted connection uses the same local port number as the listening port.

Upvotes: 1

Nikolai Fetissov
Nikolai Fetissov

Reputation: 84151

The listening socket is special. The kernel delivers to it only those TCP segments that are part of the three-way handshake, which have explicit flags in the header. Once that completes you have an established TCP connection that is identified by a full tuple (src addr, src port, dst addr, dst port).

Thus there's no ambiguity inside the network stack between listening and connected socket bound to the same local port.

It might also help to study the TCP state diagram to get a better mental picture of how all this comes together.

Upvotes: 3

Related Questions