简体   繁体   中英

Why is the Socket provided by ServerSocket using a different port?

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.

getPort() returns the remote port of the socket (ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM