Skip to content

Instantly share code, notes, and snippets.

@xexes
Forked from maciejwalkowiak/SocketUtils.java
Created December 31, 2023 13:00
Show Gist options
  • Save xexes/11d0974b22abb0a0b754286c5d2bb245 to your computer and use it in GitHub Desktop.
Save xexes/11d0974b22abb0a0b754286c5d2bb245 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