Java HTTP Port Find getAvailableListenPort()

Here you can find the source of getAvailableListenPort()

Description

A helper method to get a random free port.

License

Open Source License

Return

free port.

Declaration

public static int getAvailableListenPort() 

Method Source Code

//package com.java2s;
/**//from   www. ja  va2s  .co m
 * Copyright (c) 2017 Dell Inc., or its subsidiaries. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 */

import java.io.IOException;
import java.net.ServerSocket;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;

public class Main {
    private static final int BASE_PORT = 32768;
    private static final int MAX_PORT_COUNT = 28233;
    private static final AtomicInteger NEXT_PORT = new AtomicInteger(new Random().nextInt(MAX_PORT_COUNT));

    /**
     * A helper method to get a random free port.
     *
     * @return free port.
     */
    public static int getAvailableListenPort() {
        for (int i = 0; i < MAX_PORT_COUNT; i++) {
            int candidatePort = BASE_PORT + NEXT_PORT.getAndIncrement() % MAX_PORT_COUNT;
            try {
                ServerSocket serverSocket = new ServerSocket(candidatePort);
                serverSocket.close();
                return candidatePort;
            } catch (IOException e) {
                // Do nothing. Try another port.
            }
        }
        throw new IllegalStateException(
                String.format("Could not assign port in range %d - %d", BASE_PORT, MAX_PORT_COUNT + BASE_PORT));
    }
}

Related

  1. freePort(int suggestedPort)
  2. get(int port, String applicationRoot, String resource, String path)
  3. getAllHostNames(String hostName, int portNumber, String bindingUser)
  4. getAnonymousPort()
  5. getAnonymousPort()
  6. getAvailablePort()
  7. getAvailablePort()
  8. getAvailablePort()
  9. getAvailablePort()