Here you can find the source of getRandomAvailablePort()
public static int getRandomAvailablePort()
//package com.java2s; //License from project: Open Source License import java.net.DatagramSocket; import java.net.ServerSocket; public class Main { public static int getRandomAvailablePort() { int port = 2048; boolean br = false; while (port < 49151 && !br) { try { new ServerSocket(port).close(); new DatagramSocket(port).close(); br = true;//from w w w . ja va 2 s . c o m } catch (Exception ex) { port++; } } return port; } }