Here you can find the source of getSocketInRange(int minPort, int maxPort, boolean random)
Parameter | Description |
---|---|
minPort | minimum (inclusive) value for port. |
maxPort | max (inclusive) possible port value. |
random | true to allocate based on a random sample; false to allocate sequentially, starting from minPort. |
public static ServerSocket getSocketInRange(int minPort, int maxPort, boolean random)
//package com.java2s; // sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is import java.io.IOException; import java.net.ServerSocket; import java.util.Random; public class Main { /** Choose a port from the specified range - either sequentially, or at random. * @param minPort minimum (inclusive) value for port. * @param maxPort max (inclusive) possible port value. * @param random true to allocate based on a random sample; false to allocate sequentially, starting from minPort. * @return a ServerSocket.//from w ww. j a v a2 s.co m */ public static ServerSocket getSocketInRange(int minPort, int maxPort, boolean random) { ServerSocket s = null; int port = minPort - 1; Random r = new Random(System.currentTimeMillis()); while (s == null && port <= maxPort) { if (random) port = minPort + r.nextInt(maxPort - minPort); else port++; try { s = new ServerSocket(port); return s; // Created okay, so this port is available. } catch (IOException e) { // Try the next port. } } return null; // No port found in the allowed range. } }