Java HTTP Port Find getRandomPort()

Here you can find the source of getRandomPort()

Description

get Random Port

License

Apache License

Declaration

private static int getRandomPort() throws IOException 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.io.IOException;
import java.net.*;

public class Main {
    private static int getRandomPort() throws IOException {
        for (int port = 22332; port < 22500; port++) {
            if (trySocket(port)) {
                return port;
            }//from  w w w.  j a  v  a  2 s  . c o m
        }
        throw new IllegalStateException("Cannot find a single free port");
    }

    private static boolean trySocket(int port) throws IOException {
        InetAddress address = Inet4Address.getByName("localhost");
        ServerSocket s = null;
        try {
            s = new ServerSocket();
            s.bind(new InetSocketAddress(address, port));
            return true;
        } catch (IOException exp) {
            System.err.println("Port " + port + " already in use, tying next ...");
            // exp.printStackTrace();
            // next try ....
        } finally {
            if (s != null) {
                s.close();
            }
        }
        return false;
    }
}

Related

  1. getPrometheusMetrics(int metricsPort)
  2. getRandomAvailablePort()
  3. getRandomFreePort()
  4. getRandomFreePort()
  5. getRandomOpenPort()
  6. getRandomPort()
  7. getRandomPort()
  8. getRandomPorts(int n)
  9. getResponse(String name, String host, int port)