Here you can find the source of findAvailablePort(int port)
Determines the first available port, beginning at the specified port.
Parameter | Description |
---|---|
port | The specified port. |
public static int findAvailablePort(int port)
//package com.java2s; //License from project: LGPL import java.net.Socket; public class Main { /**// w w w . j a v a2 s . co m * <p>Determines the first available port, beginning at the specified * port. The search is abandoned after 500 increments.</p> * @param port The specified port. * @return The first available port. */ public static int findAvailablePort(int port) { int limit = 500; Socket socket; while (limit > 0) { try { socket = new Socket("localhost", port); socket.close(); limit--; port++; continue; } catch (Exception e) { // e.printStackTrace(); return port; } } return -1; } }