Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 980
user691154 Avatar asked Dec 01 '11 16:12

user691154


People also ask

What is InetSocketAddress Java?

public InetSocketAddress(int port) Creates a socket address where the IP address is the wildcard address and the port number a specified value. 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.

How to bind a port In java?

Java ServerSocket bind() methodThe bind() method of Java ServerSocket class binds the ServerSocket to the specified socket address, i.e. IP address and port number. If the specified address is null, the system will automatically pick up an ephemeral port and a valid local address to bind this socket.

What does ServerSocket bind do?

bind. Binds the ServerSocket to a specific address (IP address and port number). If the address is null , then the system will pick up an ephemeral port and a valid local address to bind the socket.


Video Answer


1 Answers

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.

like image 134
Remy Lebeau Avatar answered Sep 22 '22 03:09

Remy Lebeau