public static int getFreeRandomPort(int min, int max, int attempts) {
    """
	Find a free (on localhost) random port in the specified range after the given number of attempts.
    """
        Random random = new Random();
        for (int i=0; i < attempts; i++) {
            int port = min + random.nextInt(max - min + 1);
            try (Socket socket = new Socket("localhost", port)) {
            } catch (ConnectException e) {
                return port;
            } catch (IOException e) {
                throw new IllegalStateException("Error while trying to check open ports", e);
            }
        }
        throw new IllegalStateException("Cannot find a free random port in the range [" + min + ", " + max + "] after " + attempts + " attempts");
    }
public static int getFreeRandomPort(int min, int max, int attempts) {
        Random random = new Random();
        for (int i=0; i < attempts; i++) {
            int port = min + random.nextInt(max - min + 1);
            try (Socket socket = new Socket("localhost", port)) {
            } catch (ConnectException e) {
                return port;
            } catch (IOException e) {
                throw new IllegalStateException("Error while trying to check open ports", e);
            }
        }
        throw new IllegalStateException("Cannot find a free random port in the range [" + min + ", " + max + "] after " + attempts + " attempts");
    }
public static int getFreeRandomPort ( int min , int max , int attempts ) { Random random = new Random ( ) ; for ( int i = 0 ; i < attempts ; i ++ ) { int port = min + random . nextInt ( max - min + 1 ) ; try ( Socket socket = new Socket ( "localhost" , port ) ) { } catch ( ConnectException e ) { return port ; } catch ( IOException e ) { throw new IllegalStateException ( "Error while trying to check open ports" , e ) ; } } throw new IllegalStateException ( "Cannot find a free random port in the range [" + min + ", " + max + "] after " + attempts + " attempts" ) ; }
Find a free (on localhost) random port in the specified range after the given number of attempts.
Find a free ( on localhost ) random port in the specified range after the given number of attempts .