Java HTTP Port Find availablePort(int prefered)

Here you can find the source of availablePort(int prefered)

Description

Check whether the port is available to binding

License

Apache License

Parameter

Parameter Description
prefered a parameter

Return

-1 means not available, others means available

Declaration

public static int availablePort(int prefered) 

Method Source Code

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

import java.io.IOException;

import java.net.ServerSocket;

public class Main {
    /**/*from   ww  w . ja  va 2  s  . c  o  m*/
     * Check whether the port is available to binding
     * 
     * @param prefered
     * @return -1 means not available, others means available
     */
    public static int availablePort(int prefered) {
        int rtn = -1;
        try {
            rtn = tryPort(prefered);
        } catch (IOException e) {

        }
        return rtn;
    }

    /**
     * Check whether the port is available to binding
     * 
     * @param port
     * @return -1 means not available, others means available
     * @throws IOException
     */
    public static int tryPort(int port) throws IOException {
        ServerSocket socket = new ServerSocket(port);
        int rtn = socket.getLocalPort();
        socket.close();
        return rtn;
    }
}

Related

  1. available_port()
  2. availableAndReturn(int MIN_PORT_NUMBER, int MAX_PORT_NUMBER)
  3. availablePort()
  4. availablePort(int port)
  5. availablePort(int pPort)
  6. canConnect(String host, int port)
  7. canConnect(String host, int port)
  8. canConnectOn(String host, int port)
  9. createUnresolved(String host, int port)