Here you can find the source of searchPort(int number, int even, boolean stream)
Parameter | Description |
---|---|
number | Number of Ports requested |
even | first Port Number should be even (2) , odd (1) or random (0) |
stream | search for TCP (true) or UDP (false) Socket |
Parameter | Description |
---|---|
SocketException | an exception |
public static int searchPort(int number, int even, boolean stream) throws SocketException
//package com.java2s; import java.io.IOException; import java.net.DatagramSocket; import java.net.ServerSocket; import java.net.SocketException; import java.net.UnknownHostException; import java.util.Vector; public class Main { private static int minPort = 49152; private static int maxPort = 65535; private static Vector<Integer> assignedPorts = new Vector<Integer>(); /**/*from www .ja v a2 s. c o m*/ * * Searches for a number of successive free ports in the range between minPort and maxPort * * @param number Number of Ports requested * @param even first Port Number should be even (2) , odd (1) or random (0) * @param stream search for TCP (true) or UDP (false) Socket * @return free port number to be used (if multiple numbers were requested this * is the first of number successive numbers * @throws SocketException */ public static int searchPort(int number, int even, boolean stream) throws SocketException { boolean found = false; int offset = 0; int port = minPort; while (!found) { switch (even) { case 2: port = minPort + 2 * offset; break; case 1: port = minPort + 2 * offset + 1; break; default: port = minPort + offset; } for (int i = 0; i < number; i++) { if ((port + i) > maxPort) { throw new SocketException("No port in Range found"); } else if (!assignedPorts.contains(new Integer(port + i))) { System.err.println((port + i) + " is not assigned"); try { if (stream) { ServerSocket test = new ServerSocket(port + i); found = true; test.close(); } else { DatagramSocket test = new DatagramSocket(port + i); found = true; test.close(); } } catch (SocketException e) { found = false; offset++; break; } catch (UnknownHostException e) { // this should not happen e.printStackTrace(); } catch (IOException e) { found = false; offset++; break; } } else { found = false; offset++; break; } } } for (int i = 0; i < number; i++) { System.err.println((port + i) + " assigned"); assignedPorts.add(new Integer(port + i)); } return port; } }