Here you can find the source of getUnusedPort()
public static int getUnusedPort() throws IOException
//package com.java2s; import java.io.IOException; import java.net.ServerSocket; public class Main { /**//w ww . j a v a 2s . c o m * Get a port that isn't currently used. */ public static int getUnusedPort() throws IOException { ServerSocket s = new ServerSocket(0); int port = s.getLocalPort(); s.close(); return port; } }