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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With