Java HTTP Port Find freePort()

Here you can find the source of freePort()

Description

free Port

License

Apache License

Declaration

public static int freePort() 

Method Source Code

//package com.java2s;
/**//from   ww w  . ja  v a2  s.c o m
 * Copyright 2016 benjobs
 * <p>
 * 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
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * 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.*;
import java.net.*;
import java.util.Random;

public class Main {
    public static int freePort() {
        Random random = new Random();
        int port;
        do {
            port = random.nextInt(65535);
        } while (isLocalPortUsing(port));

        return port;
    }

    public static boolean isLocalPortUsing(int port) {
        boolean flag = true;
        try {
            flag = usingPort("127.0.0.1", port);
        } catch (Exception e) {
        }
        return flag;
    }

    /***
     *  true:already in using  false:not using
     * @param host
     * @param port
     * @throws UnknownHostException
     */
    public static boolean usingPort(String host, int port) throws UnknownHostException {
        boolean flag = false;
        InetAddress theAddress = InetAddress.getByName(host);
        try {
            new Socket(theAddress, port);
            flag = true;
        } catch (IOException e) {
        }
        return flag;
    }
}

Related

  1. findFreePortForApi()
  2. findUnusedPort()
  3. findUnusedPort()
  4. findUnusedPort(int preferredPort)
  5. findUnusedPorts(int numPorts)
  6. freePort()
  7. freePort()
  8. freePort(int suggestedPort)
  9. get(int port, String applicationRoot, String resource, String path)