Java Socket Create getSocketInRange(int minPort, int maxPort, boolean random)

Here you can find the source of getSocketInRange(int minPort, int maxPort, boolean random)

Description

Choose a port from the specified range - either sequentially, or at random.

License

Open Source License

Parameter

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.

Return

a ServerSocket.

Declaration

public static ServerSocket getSocketInRange(int minPort, int maxPort, boolean random) 

Method Source Code

//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.
    }
}

Related

  1. getSocket(String host, int port)
  2. getSocket(String host, int port, int timeout)
  3. getSocket(String i_HostName, int i_Port)
  4. getSocketFromString(String s)
  5. getSocketId(Socket socket)
  6. getSocketToBytes(String ip, int port, String packet, int timeout)
  7. getSocketToProxyServer(String host, int port)