Skip to content

Instantly share code, notes, and snippets.

@maciejwalkowiak
Last active December 31, 2023 13:00
Show Gist options
  • Save maciejwalkowiak/7390ef506be025fd43dfbdac17a726f6 to your computer and use it in GitHub Desktop.
Save maciejwalkowiak/7390ef506be025fd43dfbdac17a726f6 to your computer and use it in GitHub Desktop.
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
public class SocketUtils {
public static int findFreePort(int minPort, int maxPort) {
for (int i = minPort; i < maxPort; i++) {
if (isPortAvailable(i)) {
return i;
}
}
throw new IllegalStateException("Could not find a free TCP/IP port in range between " + minPort + " and " + maxPort);
}
public static boolean isPortAvailable(int port) {
try(ServerSocket serverSocket = new ServerSocket()) {
serverSocket.setReuseAddress(false);
serverSocket.bind(new InetSocketAddress(InetAddress.getByName("localhost"), port), 1);
return true;
} catch (Exception ex) {
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment