Here you can find the source of findAvailablePort(String hostname, int startPort, int endPort)
Parameter | Description |
---|---|
hostname | Host name |
startPort | Port number starting the range |
endPort | Port number ending the range |
public static synchronized int findAvailablePort(String hostname, int startPort, int endPort)
//package com.java2s; /*/* w ww. jav a2 s . c om*/ * Ghost4J: a Java wrapper for Ghostscript API. * * Distributable under LGPL license. * See terms of license at http://www.gnu.org/licenses/lgpl.html. */ import java.io.IOException; import java.net.InetAddress; import java.net.Socket; public class Main { /** * Finds an available port within a port range on a host * * @param hostname * Host name * @param startPort * Port number starting the range * @param endPort * Port number ending the range * @return An available port number, or 0 if none is available. */ public static synchronized int findAvailablePort(String hostname, int startPort, int endPort) { for (int port = startPort; port < (endPort + 1); port++) { try { Socket socket = new Socket(InetAddress.getByName(hostname), port); // port not available socket.close(); } catch (IOException e) { // port available return port; } } return 0; } }