Here you can find the source of findUnusedPort(InetAddress address, int from, int to)
private static int findUnusedPort(InetAddress address, int from, int to)
//package com.java2s; /******************************************************************************* * Copyright (c) 2000, 2006 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors:/*from w w w .j av a2s . co m*/ * IBM Corporation - initial API and implementation *******************************************************************************/ import java.io.*; import java.net.*; import java.util.*; public class Main { private static final Random random = new Random(System.currentTimeMillis()); private static int findUnusedPort(InetAddress address, int from, int to) { for (int i = 0; i < 12; i++) { ServerSocket ss = null; int port = getRandomPort(from, to); try { ss = new ServerSocket(); SocketAddress sa = new InetSocketAddress(address, port); ss.bind(sa); return ss.getLocalPort(); } catch (IOException e) { } finally { if (ss != null) { try { ss.close(); } catch (IOException ioe) { } } } } return -1; } private static int getRandomPort(int low, int high) { return (int) (random.nextFloat() * (high - low)) + low; } }