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?