Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

how to check the port used by the ServerSocket?

807589Nov 7 2008 — edited Nov 7 2008
From my understanding of ServerSocket, it listens for client socket to connect at a specific port and when a client establishes a connection, the server socket opens a local port on the machine to use for communication so that it can use the original port for accepting new connections. For example:
import java.net.*;

public class SimpleServer {
    public static void main(String args[]) throws Exception {
        ServerSocket serverSocket = new ServerSocket(3000);
        System.out.println("serverSocket.getLocalPort() " + serverSocket.getLocalPort());
        while (true) {
            Socket sock = serverSocket.accept();
            System.out.println("Created Socket: " + sock);
            System.out.println("getLocalPort(): " + sock.getLocalPort() + " getPort: " + sock.getPort());
        }
    }
}
As you can see, the ServerSocket is listening on port 3000. Now at runtime, I run another class which basically establishes a Socket connection. I see the following output:
serverSocket.getLocalPort() 3000
Created Socket: Socket[addr=/127.0.0.1,port=53438,localport=3000]
getLocalPort(): 3000 getPort: 53438

Both the client and server are running on the same machine. 3000 is the port where ServerSocket is listening for new socket connections, 53438 is the port of the client socket, how do I find the port number used currently by the ServerSocket to communicate with the client socket...shouldn't be 3000 cause thats where it is listening for new connections?

Thanks.
S
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Dec 5 2008
Added on Nov 7 2008
11 comments
1,054 views