Java Utililty Methods HTTP Port Find

List of utility methods to do HTTP Port Find

Description

The list of methods to do HTTP Port Find are organized into topic(s).

Method

ListgetAvailablePortsFromRange(int portMin, int portMax, int numberOfPorts)
Returns a List of available ports within a given port range.
List<Integer> availablePorts = new ArrayList<>();
int port = portMin;
int portCount = 0;
while ((portCount < numberOfPorts) && (port <= portMax)) {
    if (isPortAvailable(port)) {
        availablePorts.add(port);
        portCount++;
    port++;
return availablePorts;
intgetAvialablePort(final int basePort)
get Avialable Port
if (basePort == 0) {
    return getAvailablePort();
if (basePort < 0 || basePort > 65535) {
    throw new IllegalArgumentException("Illegal port number: " + basePort);
for (int i = basePort; i <= 65535; i++) {
    if (isPortAvailable(i)) {
...
URLgetCorrectHostnamePort(String hostPort)
Method to validate if the given String represents a hostname:port.
try {
    URL u = new URL("http://" + hostPort);
    if (u.getHost() == null) {
        throw new IllegalArgumentException(
                "The given host:port ('" + hostPort + "') doesn't contain a valid host");
    if (u.getPort() == -1) {
        throw new IllegalArgumentException(
...
intgetEffectivePort(String scheme, int specifiedPort)
get Effective Port
return specifiedPort != -1 ? specifiedPort : getDefaultPort(scheme);
intgetEphemeralPort()
get Ephemeral Port
int port = 0;
try {
    ServerSocket serverSocket = new ServerSocket(0);
    port = ((InetSocketAddress) serverSocket.getLocalSocketAddress()).getPort();
    serverSocket.close();
} catch (IOException e) {
    e.printStackTrace();
return port;
intgetFreeLocalPort()
Return usable free local port
final ServerSocket socket = new ServerSocket(0);
try {
    return socket.getLocalPort();
} finally {
    socket.close();
intgetFreePort()
Retrieve a free port.
final int port;
try (ServerSocket s = new ServerSocket(0)) {
    port = s.getLocalPort();
return port;
intgetFreePort()
Uses Minas AvailablePortFinder to find a port, starting at 14000.
int startPort = 14000;
return getFreePort(startPort);
intgetFreePort()
Return a free port which can be used to bind to
for (int start = START_PORT; start <= END_PORT; start++) {
    try {
        ServerSocket socket = new ServerSocket(start);
        socket.setReuseAddress(true);
        socket.close();
        return start;
    } catch (IOException e) {
throw new RuntimeException("Unable to find a free port....");
intgetFreePort()

Returns a free port number on localhost otherwise throws RuntimeException .

try (ServerSocket serverSocket = new ServerSocket(0)) {
    serverSocket.setReuseAddress(true);
    return serverSocket.getLocalPort();
} catch (IOException e) {
    throw new RuntimeException("Failed to get free port", e);