0
votes

Server:

int port = 7000
ServerSocket ss;
..
System.out.println("Listening on " + ss.getInetAddress() + ":"
   + ss.getLocalPort());

Socket s = ss.accept();
..
System.out.println("Accepted connection " + s.getInetAddress() + ":"
   + s.getPort());

Client:

Socket s;
..
System.out.println("Connected to " + s.getInetAddress() + ":"
   + s.getPort());

Server starts listening:

Listening on 0.0.0.0/0.0.0.0:7000

Client connects:

Connected to localhost/127.0.0.1:7000

But the server says that the socket is connected on a different port?

Accepted connection /127.0.0.1:54682

Referencing:

Java the difference of Socket and ServerSocket in using port

.. ServerSocket.accept() accepts a connection, and wraps the endpoint in a Socket. The endpoint has the same local port number as the ServerSocket, by definition as per RFC 793, and therefore so does the wrapping Socket.

and

.. each client connection will get a separate Socket to communicate on, all communicating using the same server side TCP port.

1

1 Answers

3
votes

getPort() returns the remote port of the socket (i.e. other side address) while getLocalPort() returns the local port that the socket is bound to.

If you ran s.getLocalPort()); on server accepted socket, you would get 7000 too.