Skip to content

Instantly share code, notes, and snippets.

@dhsrocha
Last active April 14, 2021 23:20
Show Gist options
  • Save dhsrocha/ea5ac7ff35d1ffc7f89cf186c8931e51 to your computer and use it in GitHub Desktop.
Save dhsrocha/ea5ac7ff35d1ffc7f89cf186c8931e51 to your computer and use it in GitHub Desktop.
Find next available TCP port.
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