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

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

Description

Search for a free TCP and UDP port in the given range

License

LGPL

Parameter

Parameter Description
start Port number start
len Range length or 0 to use up to 65535

Return

Free port number or -1 if no free port found

Declaration

public static int findFreePort(int start, int len) 

Method Source Code

//package com.java2s;

import java.net.ServerSocket;
import java.net.DatagramSocket;

public class Main {
    /**//from ww w  .ja v a  2 s  .  c  o m
     * Search for a free TCP and UDP port in the given range
     *
     * @param start Port number start
     * @param len Range length or 0 to use up to 65535
     * @return Free port number or -1 if no free port found
     */
    public static int findFreePort(int start, int len) {
        int port = start;
        int end = (len == 0) ? 65535 : start + len;
        if (end > 65535)
            end = 65535;

        while (port < end) {
            try {
                ServerSocket socket = new ServerSocket(port);
                socket.close();
            } catch (Exception e) {
                port++;
                continue;
            }

            try {
                DatagramSocket socket = new DatagramSocket(port);
                socket.close();
            } catch (Exception e) {
                port++;
                continue;
            }
            return port;
        }
        return -1;
    }
}

Related

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