Java HTTP Port Find freePort(int suggestedPort)

Here you can find the source of freePort(int suggestedPort)

Description

Returns a free port number at/above suggestedPort.

License

Open Source License

Parameter

Parameter Description
suggestedPort a parameter

Declaration

public static int freePort(int suggestedPort) 

Method Source Code


//package com.java2s;
//products where commercial interests exist (i.e., license, profit from, or

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

public class Main {
    private static final int MIN_PORT_NUMBER = 1;
    private static final int MAX_PORT_NUMBER = 65535;

    /**//from  ww w.j  a v  a2s .  c  o  m
     * Returns a free port number at/above suggestedPort.
     * @param suggestedPort
     * @return
     */
    public static int freePort(int suggestedPort) {
        while (!available(suggestedPort)) {
            suggestedPort++;
        }
        return suggestedPort;
    }

    /**
     * Checks to see if a specific port is available.
     * @see http://stackoverflow.com/questions/434718/sockets-discover-port-availability-using-java
     * @param port the port to check for availability
     */
    private static boolean available(int port) {
        if (port < MIN_PORT_NUMBER || port > MAX_PORT_NUMBER) {
            throw new IllegalArgumentException("Invalid start port: " + port);
        }

        ServerSocket ss = null;
        DatagramSocket ds = null;
        try {
            ss = new ServerSocket(port);
            ss.setReuseAddress(true);
            ds = new DatagramSocket(port);
            ds.setReuseAddress(true);
            return true;
        } catch (IOException e) {
        } finally {
            if (ds != null) {
                ds.close();
            }

            if (ss != null) {
                try {
                    ss.close();
                } catch (IOException e) {
                    /* should not be thrown */
                }
            }
        }

        return false;
    }
}

Related

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