Here you can find the source of findFreePort(InetAddress address, int start, int end)
public static int findFreePort(InetAddress address, int start, int end)
//package com.java2s; /**// ww w .j a va 2 s . c o m * Aptana Studio * Copyright (c) 2005-2011 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the GNU Public License (GPL) v3 (with exceptions). * Please see the license.html included with this distribution for details. * Any modifications to this file must keep this entire header intact. */ import java.io.IOException; import java.net.InetAddress; import java.net.ServerSocket; public class Main { /** * Find free port for the specified IP address * * @return int */ public static int findFreePort(InetAddress address) { ServerSocket socket = null; try { socket = new ServerSocket(0, 0, address); socket.setReuseAddress(true); return socket.getLocalPort(); } catch (IOException ignore) { } finally { if (socket != null) { try { socket.close(); } catch (IOException ignore) { } } } return -1; } /** * Find free port in range for the specified IP address * * @return int */ public static int findFreePort(InetAddress address, int start, int end) { ServerSocket socket = null; try { for (int port = start; port <= end; ++port) { try { socket = new ServerSocket(port, 0, address); socket.setReuseAddress(true); return socket.getLocalPort(); } catch (IOException ignore) { } } } finally { if (socket != null) { try { socket.close(); } catch (IOException ignore) { } } } return -1; } }