Here you can find the source of findFreePort(int startPort)
public static int findFreePort(int startPort)
//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; } }