-
-
Save xexes/11d0974b22abb0a0b754286c5d2bb245 to your computer and use it in GitHub Desktop.
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.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