Here you can find the source of getNextAliablePort(InetAddress address, int startport)
static public int getNextAliablePort(InetAddress address, int startport)
//package com.java2s; import java.net.*; public class Main { static public int getNextAliablePort(String address, int startport) throws UnknownHostException { InetAddress a = InetAddress.getByName(address); return getNextAliablePort(a, startport); }//from w w w. ja v a 2 s. c om static public int getNextAliablePort(InetAddress address, int startport) { int port = startport; while (port < 65535) { try { Socket socket = new Socket(address, port); socket.close(); port++; } catch (Exception ex) { return port; } } return -1; } }