Created
February 15, 2016 14:26
-
-
Save belano/75d4c3c5c868f752eeaa to your computer and use it in GitHub Desktop.
Allocate free port from an ephemeral port range
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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