Here you can find the source of getAvailablePort(int randomAttempts)
Parameter | Description |
---|---|
randomAttempts | no of times to TEST port numbers picked randomly over the given range |
public static synchronized int getAvailablePort(int randomAttempts)
//package com.java2s; //License from project: Apache License import java.io.IOException; import java.net.DatagramSocket; import java.net.ServerSocket; import java.util.ArrayList; import java.util.Random; public class Main { public static final int MIN_PORT_NUMBER = 9000; public static final int MAX_PORT_NUMBER = 11000; /**// w ww.j a v a2 s. co m * Attempts to find a free port between the MIN_PORT_NUMBER(9000) and MAX_PORT_NUMBER(11000). * Tries 'RANDOMLY picked' port numbers between this range up-until "randomAttempts" number of * times. If still fails, then tries each port in descending order from the MAX_PORT_NUMBER * whilst skipping already attempted ones via random selection. * * @param randomAttempts no of times to TEST port numbers picked randomly over the given range * @return an available/free port */ public static synchronized int getAvailablePort(int randomAttempts) { ArrayList<Integer> failedPorts = new ArrayList<Integer>(randomAttempts); Random randomNum = new Random(); int randomPort = MAX_PORT_NUMBER; while (randomAttempts > 0) { randomPort = randomNum.nextInt(MAX_PORT_NUMBER - MIN_PORT_NUMBER) + MIN_PORT_NUMBER; if (checkIfPortAvailable(randomPort)) { return randomPort; } failedPorts.add(randomPort); randomAttempts--; } randomPort = MAX_PORT_NUMBER; while (true) { if (!failedPorts.contains(randomPort) && checkIfPortAvailable(randomPort)) { return randomPort; } randomPort--; } } private static boolean checkIfPortAvailable(int port) { ServerSocket tcpSocket = null; DatagramSocket udpSocket = null; try { tcpSocket = new ServerSocket(port); tcpSocket.setReuseAddress(true); udpSocket = new DatagramSocket(port); udpSocket.setReuseAddress(true); return true; } catch (IOException ex) { // denotes the port is in use } finally { if (tcpSocket != null) { try { tcpSocket.close(); } catch (IOException e) { /* not to be thrown */ } } if (udpSocket != null) { udpSocket.close(); } } return false; } }