Java HTTP Port Find getAvailablePort(int randomAttempts)

Here you can find the source of getAvailablePort(int randomAttempts)

Description

Attempts to find a free port between the MIN_PORT_NUMBER(9000) and MAX_PORT_NUMBER(11000).

License

Apache License

Parameter

Parameter Description
randomAttempts no of times to TEST port numbers picked randomly over the given range

Return

an available/free port

Declaration

public static synchronized int getAvailablePort(int randomAttempts) 

Method Source Code

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

import java.io.IOException;
import java.net.DatagramSocket;

import java.net.ServerSocket;

import java.util.ArrayList;

import java.util.Random;

public class Main {
    public static final int MIN_PORT_NUMBER = 9000;
    public static final int MAX_PORT_NUMBER = 11000;

    /**// w  ww.j  a  v a2 s.  co  m
     * Attempts to find a free port between the MIN_PORT_NUMBER(9000) and MAX_PORT_NUMBER(11000).
     * Tries 'RANDOMLY picked' port numbers between this range up-until "randomAttempts" number of
     * times. If still fails, then tries each port in descending order from the MAX_PORT_NUMBER
     * whilst skipping already attempted ones via random selection.
     *
     * @param randomAttempts no of times to TEST port numbers picked randomly over the given range
     * @return an available/free port
     */
    public static synchronized int getAvailablePort(int randomAttempts) {
        ArrayList<Integer> failedPorts = new ArrayList<Integer>(randomAttempts);

        Random randomNum = new Random();
        int randomPort = MAX_PORT_NUMBER;

        while (randomAttempts > 0) {
            randomPort = randomNum.nextInt(MAX_PORT_NUMBER - MIN_PORT_NUMBER) + MIN_PORT_NUMBER;

            if (checkIfPortAvailable(randomPort)) {
                return randomPort;
            }
            failedPorts.add(randomPort);
            randomAttempts--;
        }

        randomPort = MAX_PORT_NUMBER;

        while (true) {
            if (!failedPorts.contains(randomPort) && checkIfPortAvailable(randomPort)) {
                return randomPort;
            }
            randomPort--;
        }
    }

    private static boolean checkIfPortAvailable(int port) {
        ServerSocket tcpSocket = null;
        DatagramSocket udpSocket = null;

        try {
            tcpSocket = new ServerSocket(port);
            tcpSocket.setReuseAddress(true);

            udpSocket = new DatagramSocket(port);
            udpSocket.setReuseAddress(true);
            return true;
        } catch (IOException ex) {
            // denotes the port is in use
        } finally {
            if (tcpSocket != null) {
                try {
                    tcpSocket.close();
                } catch (IOException e) {
                    /* not to be thrown */
                }
            }

            if (udpSocket != null) {
                udpSocket.close();
            }
        }

        return false;
    }
}

Related

  1. getAvailablePort(final int basePort)
  2. getAvailablePort(int defaultPort)
  3. getAvailablePort(int port)
  4. getAvailablePort(int port)
  5. getAvailablePort(int prefferedPort)
  6. getAvailablePort(int startPort)
  7. getAvailablePort(String hostname, String portRange)
  8. getAvailablePorts(int basePort, int portCount)
  9. getAvailablePortsFromRange(int portMin, int portMax, int numberOfPorts)