Java HTTP Port Find findFreePort(int startPort)

Here you can find the source of findFreePort(int startPort)

Description

find Free Port

License

Mozilla Public License

Declaration

public static int findFreePort(int startPort) 

Method Source Code

//package com.java2s;
/*****************************************************************************************
 * *** BEGIN LICENSE BLOCK *****/*from w  w w.j  a v a  2 s .co  m*/
 *
 * Version: MPL 2.0
 *
 * echocat jConscius, Copyright (c) 2010-2012 echocat
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * *** END LICENSE BLOCK *****
 ****************************************************************************************/

import java.net.InetSocketAddress;
import java.net.Socket;

public class Main {
    public static int findFreePort(int startPort) {
        int current = startPort;
        boolean found = false;
        while (!found) {
            final Socket socket = new Socket();
            try {
                socket.connect(new InetSocketAddress("127.0.0.1", current), 100);
                current++;
            } catch (Exception ignored) {
                found = true;
            } finally {
                try {
                    socket.close();
                } catch (Exception ignored) {
                }
            }
        }
        return current;
    }
}

Related

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