Java HTTP Port Find findAvailablePort()

Here you can find the source of findAvailablePort()

Description

Requests a random server socket port to be created, closes it, and returns the port picked as a potentially available port.

License

Open Source License

Declaration

public static int findAvailablePort() 

Method Source Code


//package com.java2s;
/*//from   w w  w  .j a v a  2  s.  co m
 * Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
 *
 * 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;

import java.util.logging.Logger;

public class Main {
    /**
     * Requests a random server socket port to be created, closes it, and returns the port picked
     * as a potentially available port. Note, that this is not an atomic probe and acquire, so the port
     * might be taken by the time a bind occurs.
     */
    public static int findAvailablePort() {
        int port = 0;
        ServerSocket socket = null;
        try {
            socket = new ServerSocket(0);
            socket.setReuseAddress(true);
            port = socket.getLocalPort();
            Logger.getAnonymousLogger().info("port candidate:" + port);
        } catch (Throwable e) {
            Logger.getAnonymousLogger().severe(e.toString());
        } finally {
            try {
                if (socket != null) {
                    socket.close();
                }
            } catch (IOException e) {
            }
        }
        return port;
    }
}

Related

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