Java HTTP Port Find findAvailablePort()

Here you can find the source of findAvailablePort()

Description

find Available Port

License

Apache License

Declaration

public static int findAvailablePort() throws IOException 

Method Source Code

//package com.java2s;
/*/*from   ww  w .j  av  a 2s  . c  o  m*/
 * Copyright 2014 NAVER Corp.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

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

public class Main {
    public static int findAvailablePort() throws IOException {
        return findAvailablePort(21111);
    }

    public static int findAvailablePort(int defaultPort) throws IOException {
        int bindPort = defaultPort;

        ServerSocket serverSocket = null;
        while (0xFFFF >= bindPort && serverSocket == null) {
            try {
                serverSocket = new ServerSocket(bindPort);
            } catch (IOException ex) {
                bindPort++;
            }
        }

        if (serverSocket != null) {
            serverSocket.close();
            return bindPort;
        }

        throw new IOException("can't find avaiable port.");
    }
}

Related

  1. canConnectOn(String host, int port)
  2. createUnresolved(String host, int port)
  3. doSend(String command, String server, String port)
  4. executeHttpCommand(String host, int port, String request, String charset)
  5. exportResource(Class fromClass, String resourceName, String exportPath)
  6. findAvailablePort()
  7. findAvailablePort()
  8. findAvailablePort(int min, int max)
  9. findAvailablePort(int minPort, int maxPort)