Here you can find the source of getAvailablePort(String hostname, String portRange)
public static int getAvailablePort(String hostname, String portRange) throws IOException
//package com.java2s; /*/*from ww w.j a v a 2 s. c o m*/ * Copyright 2005 Sun Microsystems, Inc. * Copyright 2005 GigaSpaces, Inc. * * Licensed 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 * * http://www.apache.org/licenses/LICENSE-2.0 * * 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.IOException; import java.net.ServerSocket; import java.util.StringTokenizer; public class Main { public static int getAvailablePort(String hostname, String portRange) throws IOException { StringTokenizer st = new StringTokenizer(portRange, ","); while (st.hasMoreTokens()) { int index = portRange.indexOf('-'); if (index == -1) { int port = Integer.parseInt(st.nextToken().trim()); if (port == 0) { return 0; } try { return getPort(port); } catch (IOException e) { // can't create one } } else { int startPort = Integer.parseInt(portRange.substring(0, index)); int endPort = Integer.parseInt(portRange.substring(index + 1)); if (endPort < startPort) { throw new IllegalArgumentException( "Start port [" + startPort + "] must be greater than end port [" + endPort + "]"); } for (int i = startPort; i <= endPort; i++) { try { return getPort(i); } catch (IOException ex) { // can't create ont } } } } throw new IOException("Failed to get free port from [" + portRange + "]"); } /** * This method checks whether supplied port is free. * * If port 0 returns an anonymous port. */ private static int getPort(int port) throws IOException { ServerSocket socket = null; try { socket = new ServerSocket(port); return socket.getLocalPort(); } finally { if (socket != null) { try { socket.close(); } catch (IOException ex) { /* don't care */ } } } } }