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.DatagramSocket; import java.net.ServerSocket; import java.util.Random; public class Main { /**//from w w w .ja v a2 s . co m * Getting a available port on range 60000:61000 * @return */ public static int getAvailablePort() { int initialP = 60000; int finalP = 61000; for (int i = initialP; i < finalP; i++) { int port = new Random().nextInt(finalP - initialP) + initialP; ServerSocket ss = null; DatagramSocket ds = null; try { ss = new ServerSocket(port); ss.setReuseAddress(true); ds = new DatagramSocket(port); ds.setReuseAddress(true); return port; } catch (IOException e) { } finally { if (ds != null) { ds.close(); } if (ss != null) { try { ss.close(); } catch (IOException e) { /* should not be thrown */ } } } } return -1; } }