Java HTTP Port Find findUnusedPorts(int numPorts)

Here you can find the source of findUnusedPorts(int numPorts)

Description

Finds a number of unused TCP ports.

License

Apache License

Parameter

Parameter Description
numPorts The number of free ports to look for.

Exception

Parameter Description
RuntimeException if no free ports were found

Return

A list of ports that were not allocated at the time this method was invoked.

Declaration

public static List<Integer> findUnusedPorts(int numPorts) throws RuntimeException 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.io.IOException;
import java.net.ServerSocket;
import java.util.List;
import com.google.common.collect.Lists;
import com.google.common.io.Closer;

public class Main {
    /**/*  ww w  .j av a2 s.co  m*/
     * Finds a number of unused TCP ports.
     * <p/>
     * <i>Note that there are no guarantees that the ports are still available
     * when this method returns</i>.
     *
     * @param numPorts
     *            The number of free ports to look for.
     * @return A list of ports that were not allocated at the time this method
     *         was invoked.
     * @throws RuntimeException
     *             if no free ports were found
     */
    public static List<Integer> findUnusedPorts(int numPorts) throws RuntimeException {
        Closer closer = Closer.create();
        List<Integer> freePorts = Lists.newArrayListWithCapacity(numPorts);
        try {
            // collect free port sockets
            for (int i = 0; i < numPorts; i++) {
                try {
                    ServerSocket serverSocket = new ServerSocket(0);
                    closer.register(serverSocket);
                    freePorts.add(serverSocket.getLocalPort());
                } catch (IOException e) {
                    throw new RuntimeException("failed to find free ports: " + e.getMessage(), e);
                }
            }
        } finally {
            // release sockets
            try {
                closer.close();
            } catch (IOException e) {
                throw new RuntimeException("failed to close probed port: " + e.getMessage(), e);
            }
        }
        return freePorts;
    }
}

Related

  1. findFreePortExcepting(int portToExclude)
  2. findFreePortForApi()
  3. findUnusedPort()
  4. findUnusedPort()
  5. findUnusedPort(int preferredPort)
  6. freePort()
  7. freePort()
  8. freePort()
  9. freePort(int suggestedPort)