Last active
April 14, 2021 23:20
-
-
Save dhsrocha/ea5ac7ff35d1ffc7f89cf186c8931e51 to your computer and use it in GitHub Desktop.
Find next available TCP port.
This file contains hidden or 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.net.ServerSocket; | |
class PortUtil { | |
private PortUtil() {} | |
/** | |
* Recursively loops until finding a available TCP port, locks it, get | |
* its value and then releases it. | |
* | |
* @return next available port. | |
*/ | |
static int nextAvailablePort() { | |
try (var s = new ServerSocket(0)) { | |
return s.getLocalPort(); | |
} catch (final IOException e) { | |
return nextAvailablePort(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment