Java HTTP Port Find getAvailablePort()

Here you can find the source of getAvailablePort()

Description

get one available port

License

Apache License

Return

-1 means failed, others means one availablePort

Declaration

public static int getAvailablePort() 

Method Source Code

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

import java.io.IOException;

import java.net.ServerSocket;

public class Main {
    /**/*  w w  w  .ja va2  s .c o m*/
     * get one available port
     * 
     * @return -1 means failed, others means one availablePort
     */
    public static int getAvailablePort() {
        return availablePort(0);
    }

    /**
     * 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. getAvailablePort()
  2. getAvailablePort()
  3. getAvailablePort()
  4. getAvailablePort()
  5. getAvailablePort()
  6. getAvailablePort()
  7. getAvailablePort(final int basePort)
  8. getAvailablePort(int defaultPort)
  9. getAvailablePort(int port)