Here you can find the source of getAvailablePort()
public static int getAvailablePort()
//package com.java2s; //License from project: Open Source License import java.io.IOException; import java.net.ServerSocket; public class Main { public static int getAvailablePort() { int port = -1; try {//from www .j ava2 s. co m ServerSocket server = new ServerSocket(0); port = server.getLocalPort(); server.close(); } catch (IOException exception) { port = -1; } return port; } }