Java HTTP Port Find getAvailablePort()

Here you can find the source of getAvailablePort()

Description

get Available Port

License

EUPL

Declaration

public static int getAvailablePort() 

Method Source Code

//package com.java2s;
/*/*  w  w  w  . j av  a  2 s  . com*/
 * Copyright 2013 SmartBear Software
 * 
 * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by the European Commission - subsequent
 * versions of the EUPL (the "Licence");
 * You may not use this work except in compliance with the Licence.
 * You may obtain a copy of the Licence at:
 * 
 * http://ec.europa.eu/idabc/eupl
 * 
 * Unless required by applicable law or agreed to in writing, software distributed under the Licence is
 * distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied. See the Licence for the specific language governing permissions and limitations
 * under the Licence.
 */

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

public class Main {
    public static int getAvailablePort() {

        try (ServerSocket ss = new ServerSocket(0)) {
            ss.setReuseAddress(true);
            return ss.getLocalPort();
        } catch (IOException e) {
        } finally {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        return -1;
    }

    public static int getAvailablePort(int start) {
        while (!isPortAvailable(start))
            start++;

        return start;
    }

    public static boolean isPortAvailable(int port) {
        try (ServerSocket ss = new ServerSocket(port)) {
            ss.setReuseAddress(true);
            return true;
        } catch (IOException e) {
        }

        return false;
    }
}

Related

  1. get(int port, String applicationRoot, String resource, String path)
  2. getAllHostNames(String hostName, int portNumber, String bindingUser)
  3. getAnonymousPort()
  4. getAnonymousPort()
  5. getAvailableListenPort()
  6. getAvailablePort()
  7. getAvailablePort()
  8. getAvailablePort()
  9. getAvailablePort()