Java HTTP Port Find findUnusedPort()

Here you can find the source of findUnusedPort()

Description

find Unused Port

License

Apache License

Declaration

public static int findUnusedPort() throws IOException 

Method Source Code


//package com.java2s;
/*//from w w  w .ja v  a  2  s .  c o  m
 * Copyright 2010 Proofpoint, Inc.
 *
 * 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.InetSocketAddress;
import java.net.ServerSocket;

public class Main {
    public static int findUnusedPort() throws IOException {
        int port;

        ServerSocket socket = new ServerSocket();
        try {
            socket.bind(new InetSocketAddress(0));
            port = socket.getLocalPort();
        } finally {
            socket.close();
        }

        return port;
    }
}

Related

  1. findFreePort(int startPort)
  2. findFreePort(int startPort)
  3. findFreePortExcepting(int portToExclude)
  4. findFreePortForApi()
  5. findUnusedPort()
  6. findUnusedPort(int preferredPort)
  7. findUnusedPorts(int numPorts)
  8. freePort()
  9. freePort()