10/02/2012

[Java] Find free port

Getting the number of an unused port on the system via Java 7 is as easy as:


import java.net.ServerSocket;


public static int findFreePort(){
int port = 0;
try(ServerSocket server = new ServerSocket(0);){
port = server.getLocalPort();
}catch(Exception e){
System.err.println("unable to find a free port");
return null;
}
return port;
}


We do not need to call a server.close() since Java 7 does that automatically for us as we used the new try-catch block with resources declaration

2 comments:

With great power comes great responsibility.

Da grandi poteri derivano grandi responsabilità.