Here you can find the source of available_port()
public static int available_port()
//package com.java2s; //License from project: Apache License import java.io.IOException; import java.net.ServerSocket; public class Main { public static int available_port() { return available_port(0); }//w ww.j a va 2 s .c o m public static int available_port(int prefered) { int rtn = -1; try { rtn = try_port(prefered); } catch (IOException e) { rtn = available_port(); } return rtn; } public static int try_port(int port) throws IOException { ServerSocket socket = new ServerSocket(port); int rtn = socket.getLocalPort(); socket.close(); return rtn; } }