Java HTTP Port Find findAvailablePorts(int n)

Here you can find the source of findAvailablePorts(int n)

Description

find Available Ports

License

Open Source License

Declaration

public static int[] findAvailablePorts(int n) throws IOException 

Method Source Code

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

Related

  1. findAvailablePort(int min, int max)
  2. findAvailablePort(int minPort, int maxPort)
  3. findAvailablePort(int port)
  4. findAvailablePort(int port)
  5. findAvailablePort(String hostname, int startPort, int endPort)
  6. findFreePort()
  7. findFreePort()
  8. findFreePort()
  9. findFreePort()