Java HTTP Port Find findFreePortExcepting(int portToExclude)

Here you can find the source of findFreePortExcepting(int portToExclude)

Description

Finds a free port on the machine, but allow the ability to specify a port number to not use, no matter what.

License

Apache License

Declaration

public static int findFreePortExcepting(int portToExclude) throws IOException 

Method Source Code

//package com.java2s;
/**/*from  w  ww  . ja  v a2 s.c o m*/
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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 {
    /**
     * Finds a free port on the machine, but allow the
     * ability to specify a port number to not use, no matter what.
     */
    public static int findFreePortExcepting(int portToExclude) throws IOException {
        ServerSocket socket1 = null;
        ServerSocket socket2 = null;
        try {
            socket1 = new ServerSocket(0);
            socket2 = new ServerSocket(0);
            if (socket1.getLocalPort() != portToExclude) {
                return socket1.getLocalPort();
            }
            // If we're here, then socket1.getLocalPort was the port to exclude
            // Since both sockets were open together at a point in time, we're
            // guaranteed that socket2.getLocalPort() is not the same.
            return socket2.getLocalPort();
        } finally {
            if (socket1 != null) {
                socket1.close();
            }
            if (socket2 != null) {
                socket2.close();
            }
        }
    }
}

Related

  1. findFreePort()
  2. findFreePort(int start, int len)
  3. findFreePort(int start, int limit)
  4. findFreePort(int startPort)
  5. findFreePort(int startPort)
  6. findFreePortForApi()
  7. findUnusedPort()
  8. findUnusedPort()
  9. findUnusedPort(int preferredPort)