I understand that the following code can (perhaps not very efficiently) find out a free TCP port in Java:
public static int findFreePort() {
int port;
try {
ServerSocket socket= new ServerSocket(0);
port = socket.getLocalPort();
socket.close();
} catch (Exception e) { port = -1; }
return port;
}
(There are some related questions here in SO – for example).
What I don’t understand is why (or whether) two succesive calls to this method are guaranteed to return two different ports. This is assumed, for example, here (search for the calls to findFreePort method).
Is this correct?
In the Javadoc specification, I don’t see any line saying that two succesive calls is guaranteed to return two different ports…
Since the ServerSocket is closed, a second call could give the same port. Statistically, it is unprobable but not impossible I think.
If you open your two ServerSocket, get the ports, and then, close your two ServerSocket, you are guarranted to get two different ports (since the first is not free when you create the second ServerSocket).
Example method to get n different free ports :