Here you can find the source of findAvailablePort(int minPort, int maxPort)
public static ServerSocket findAvailablePort(int minPort, int maxPort) throws IOException
//package com.java2s; //License from project: Apache License import java.io.IOException; import java.net.ServerSocket; public class Main { private static final Object lock = new Object(); public static ServerSocket findAvailablePort(int minPort, int maxPort) throws IOException { synchronized (lock) { for (int i = minPort; i < maxPort; i++) { try { return new ServerSocket(i); } catch (IOException ex) { // try next port }/*from w ww . j av a 2 s .c om*/ } } // if the program gets here, no port in the range was found throw new IOException("no available port found"); } }