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.*; import java.util.Random; public class Main { private static final int RND_PORT_START = 30000; private static final int RND_PORT_RANGE = 10000; private static final Random RANDOM = new Random(System.currentTimeMillis()); private static final int MAX_PORT = 65535; public static int getAvailablePort() { ServerSocket ss = null;/*from w ww . jav a 2 s . c om*/ try { ss = new ServerSocket(); ss.bind(null); return ss.getLocalPort(); } catch (IOException e) { return getRandomPort(); } finally { if (ss != null) { try { ss.close(); } catch (IOException e) { } } } } public static int getAvailablePort(int port) { if (port <= 0) { return getAvailablePort(); } for (int i = port; i < MAX_PORT; i++) { ServerSocket ss = null; try { ss = new ServerSocket(i); return i; } catch (IOException e) { // continue } finally { if (ss != null) { try { ss.close(); } catch (IOException e) { } } } } return port; } public static int getRandomPort() { return RND_PORT_START + RANDOM.nextInt(RND_PORT_RANGE); } }