Here you can find the source of getNextAvailablePort(int port)
public static int getNextAvailablePort(int port)
//package com.java2s; import java.io.IOException; import java.net.Socket; public class Main { public static int getNextAvailablePort(int port) { int offset = detectPortOffset(port); if (offset < 0) { //FIXME that's really an error return port; }// www . j a va2 s. c o m return port + offset; } public static int detectPortOffset(int port) { for (int offset = 0; offset < 100; offset++) { int newPort = port + offset; try (Socket socket = new Socket("localhost", newPort)) { } catch (IOException ignored) { return offset; } } return -1;//TODO handle error? } }