Here you can find the source of getAvailablePort()
public static int getAvailablePort()
//package com.java2s; //License from project: Apache License import java.io.IOException; import java.net.ServerSocket; public class Main { /**/* w w w .ja va2 s .c o m*/ * get one available port * * @return -1 means failed, others means one availablePort */ public static int getAvailablePort() { return availablePort(0); } /** * Check whether the port is available to binding * * @param prefered * @return -1 means not available, others means available */ public static int availablePort(int prefered) { int rtn = -1; try { rtn = tryPort(prefered); } catch (IOException e) { } return rtn; } /** * Check whether the port is available to binding * * @param port * @return -1 means not available, others means available * @throws IOException */ public static int tryPort(int port) throws IOException { ServerSocket socket = new ServerSocket(port); int rtn = socket.getLocalPort(); socket.close(); return rtn; } }