Search code examples
javasocketsjava-5

which ephemeral port has java InetSocketAddress binded to?


What I'd like to achieve

bind a server to an ephemeral port for unit testing purposes.

My issue :

Using the 1.5.0_22 JDK I try to bind an InetSocketAddress on an ephemeral port using port 0 as per the javadoc but I can't find a way from the address object to know which port it has binded to, so I cannot have my clients configured accordingly:

InetSocketAddress address = new InetSocketAddress(0);
assertThat(address.isUnresolved(), is(false));
assertThat(address.getPort(), is(0));

I might not understand the javadoc sentence correctly :

A valid port value is between 0 and 65535. A port number of zero will let the system pick up an ephemeral port in a bind operation.

But checking the port even after having my server listening to the socket (I'm assuming the binding had happened then) does not returns anything else but 0 (the following uses the http://simpleweb.sourceforge.net/ library) :

    Container httpServer = new Container() {

        public void handle(Request req, Response resp) {
        }
    };
    SocketConnection connection = new SocketConnection(httpServer);
    InetSocketAddress address = new InetSocketAddress(0);
    connection.connect(address);

    assertThat(address.isUnresolved(), is(false));
    assertThat(address.getPort(), is(0));

Using nmap I don't even see a binded port so I'm assuming my understanding is incorrect. Any help?


Solution

  • The InetSocketAddress that initially contains port 0 is not updated by connect() to represent the actual port that was bound to. Call connection.getLocalPort() or ((InetSocketAddress)connection.getLocalSocketAddress()).getPort() instead to get the bound port.