Skip to content

Instantly share code, notes, and snippets.

@belano
Created February 15, 2016 14:26
Show Gist options
  • Save belano/75d4c3c5c868f752eeaa to your computer and use it in GitHub Desktop.
Save belano/75d4c3c5c868f752eeaa to your computer and use it in GitHub Desktop.
Allocate free port from an ephemeral port range
import java.io.IOException;
import java.net.ServerSocket;
public final class Network {
private Network() {
// Do nothing.
}
public static int findFreePort() {
try (ServerSocket socket = new ServerSocket(0)) {
return socket.getLocalPort();
} catch (IOException e) {
throw new UnsupportedOperationException("Socket Exception while opening socket.", e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment