Java HTTP Port Find findFreePort(int start, int limit)

Here you can find the source of findFreePort(int start, int limit)

Description

find Free Port

License

Apache License

Declaration

public static int findFreePort(int start, int limit) 

Method Source Code

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

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class Main {
    public static int findFreePort(int start, int limit) {
        if (start == 0) {
            //bail out if the default is "dont care"
            return 0;
        }//from ww  w .  j a v a  2  s . co m
        int found = 0;
        int port = start;
        int finish = start + limit;
        while (found == 0 && port < finish) {
            if (isPortAvailable(port)) {
                found = port;
            } else {
                port++;
            }
        }
        return found;
    }

    /**
     * See if a port is available for listening on by trying to listen
     * on it and seeing if that works or fails.
     *
     * @param port port to listen to
     * @return true if the port was available for listening on
     */
    public static boolean isPortAvailable(int port) {
        try {
            ServerSocket socket = new ServerSocket(port);
            socket.close();
            return true;
        } catch (IOException e) {
            return false;
        }
    }

    /**
     * See if a port is available for listening on by trying connect to it
     * and seeing if that works or fails
     *
     * @param host
     * @param port
     * @return
     */
    public static boolean isPortAvailable(String host, int port) {
        try {
            Socket socket = new Socket(host, port);
            socket.close();
            return false;
        } catch (IOException e) {
            return true;
        }
    }
}

Related

  1. findFreePort()
  2. findFreePort()
  3. findFreePort()
  4. findFreePort()
  5. findFreePort(int start, int len)
  6. findFreePort(int startPort)
  7. findFreePort(int startPort)
  8. findFreePortExcepting(int portToExclude)
  9. findFreePortForApi()