Java HTTP Port Find randomAvailablePort()

Here you can find the source of randomAvailablePort()

Description

random Available Port

License

Apache License

Return

a random available port for binding

Declaration

static int randomAvailablePort() 

Method Source Code

//package com.java2s;
/*//  w  ww.  j av a 2s.com
 * Licensed to CRATE Technology GmbH ("Crate") under one or more contributor
 * license agreements.  See the NOTICE file distributed with this work for
 * additional information regarding copyright ownership.  Crate 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.
 *
 * However, if you have executed another commercial license agreement
 * with Crate these terms will supersede the license and you may use the
 * software solely pursuant to the terms of the relevant commercial agreement.
 */

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

import java.util.concurrent.ThreadLocalRandom;

public class Main {
    /**
     * @return a random available port for binding
     */
    static int randomAvailablePort() {
        try {
            ServerSocket socket = new ServerSocket(0);
            int port = socket.getLocalPort();
            socket.close();
            return port;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    static int randomAvailablePort(int from, int to) {
        int repeat = 5;
        while (repeat > 0)
            try {
                int port = ThreadLocalRandom.current().nextInt(from, to + 1);
                ServerSocket socket = new ServerSocket(port);
                socket.close();
                return port;
            } catch (IOException ignored) {
                repeat--;
            }
        throw new RuntimeException("no free port found");
    }
}

Related

  1. parseCommaDelimitedHosts2(String hosts, int port_range)
  2. parseHostPort(String s)
  3. parsePort(String s)
  4. ping(String domain, int port)
  5. pingServer(String host, Integer port)
  6. randomFreePort()
  7. randomFreePort()
  8. randomFreePort()
  9. read(String host, int port)