Here you can find the source of findAvailablePorts(int n)
public static int[] findAvailablePorts(int n) throws IOException
//package com.java2s; /*-//from www .jav a2s . co m * See the file LICENSE for redistribution information. * * Copyright (c) 2010, 2011 Oracle and/or its affiliates. All rights reserved. * */ import java.io.IOException; import java.net.ServerSocket; public class Main { public static int[] findAvailablePorts(int n) throws IOException { int ports[] = new int[n]; ServerSocket[] sockets = new ServerSocket[n]; for (int i = 0; i < n; i++) { ServerSocket s = new ServerSocket(0); s.setReuseAddress(true); ports[i] = s.getLocalPort(); sockets[i] = s; } for (int i = 0; i < n; i++) sockets[i].close(); return ports; } }