Search code examples
javasocketstcpserversocket

In TCP MultiThreaded Server, if a client gets service ,how to find the port number of servicing socket?


In TCP Multi Threaded Server, if a client gets service ,how to find the port number of servicing socket?

From Sun Java tutorials

When a connection is requested and successfully established, the accept() method returns a new "Socket object" which is bound to the same local port and has its remote address and remote port set to that of the client. The server can communicate with the client over this new Socket and continue to listen for client connection requests on the original ServerSocket.

How can I find the port number of the "Socket object"?


Solution

  • Does Socket.getPort() not do what you want? Or do you mean you want the local port (again, there's Socket.getLocalPort()? If you could give a worked example of what you're after, it would be easier to understand.

    Here's a short example:

    import java.net.*;
    
    public class Test {
        public static void main(String[] args) throws Exception {
            ServerSocket ss = new ServerSocket(50000);
            while (true) {
                Socket s = ss.accept();
                System.out.println("Local: " + s.getLocalPort() + 
                                   "; Remote: " + s.getPort());
            }
        }
    }
    

    If you run that code and connect to it multiple times, you'll get output something like this:

    Local: 50000; Remote: 17859
    Local: 50000; Remote: 17866
    Local: 50000; Remote: 17872
    

    So getLocalPort() returns the port that was specified in the ServerSocket constructor, but getPort() returns a different port each time.