Why Java ServerSocket accept() returns a socket with the same port as ServerSocket?

WoooHaaaa picture WoooHaaaa · Dec 30, 2012 · Viewed 7.4k times · Source

In the server side, i use this code :

ServerSocket server = new ServerSocket(1234);
Socket server_socket = server.accept();

I found the server is listening on port 1234.

When one or more client sockets are connected, they are all using the same port 1234 !

That is really confusing :

enter image description here

I remember that multi sockets can't use the same port, isn't it right ? Thanks.

Answer

John Dvorak picture John Dvorak · Dec 30, 2012

A TCP connection is identified by four numbers:

  • client (or peer 1) IP
  • server (or peer 2) IP
  • client port
  • server port

A typical TCP connection is open as follows:

  • The client IP is given by the client's ISP or NAT.
  • The server IP is given by the user or looked up in a DNS.
  • The client chooses a port arbitrarily from the unassigned range (while avoiding duplicate quadruples)
  • The server port is given by the protocol or explicitly.

The port that you specify in the ServerSocket is the one the clients connect to. It's nothing more than a port number that the OS knows that belongs to your application and an object that passes the events from the OS to your application.

The ServerSocket#accept method returns a Socket. A Socket is an object that wraps a single TCP connection. That is, the client IP, the server IP, the client TCP port and the server TCP port (and some methods to pass the associated data around)

The first TCP packet that the client sends must contain the server port that your app listens on, otherwise the operating system wouldn't know what application the connection belongs to.

Further on, there is no incentive to switch the server TCP port to another number. It doesn't help the server machine OR the client machine, it needs some overhead to perform (you need to send the new and the old TCP port together), and there's additional overhead, since the server OS can no longer identify the application by a single port - it needs to associate the application with all server ports it uses (the clients still needs to do it, but a typical client has less connections than a typical server)


What you see is

  • two inbound connections, belonging to the server (local port:1234). Each has its own Socket in the server application.
  • two outbound connections, belonging to the client (remote port:1234). Each has its own Socket in the client application.
  • one listening connection, belonging to the server. This corresponds to the single ServerSocket that accepts connections.

Since they are loopback connections, you can see both endpoints mixed together on a single machine. You can also see two distinct client ports (52506 and 52511), both on the local side and on the remote side.