Last active
December 31, 2023 13:00
-
-
Save maciejwalkowiak/7390ef506be025fd43dfbdac17a726f6 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