Here you can find the source of getPorts(int count)
Parameter | Description |
---|---|
count | Number of local ports to identify and return. |
Parameter | Description |
---|---|
RuntimeException | if an I/O error occurs opening or closing a socket. |
public static int[] getPorts(int count)
//package com.java2s; /**//from w ww . j a v a 2 s . co m * Copyright 2015 Cerner Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.IOException; import java.net.ServerSocket; import java.util.HashSet; import java.util.Set; public class Main { private static final Set<Integer> USED_PORTS = new HashSet<Integer>(); /** * Returns an array containing the specified number of available local ports. * * @param count Number of local ports to identify and return. * * @return an array of available local port numbers. * * @throws RuntimeException if an I/O error occurs opening or closing a socket. */ public static int[] getPorts(int count) { int[] ports = new int[count]; Set<ServerSocket> openSockets = new HashSet<ServerSocket>(count + USED_PORTS.size()); for (int i = 0; i < count;) { try { ServerSocket socket = new ServerSocket(0); int port = socket.getLocalPort(); openSockets.add(socket); // Disallow port reuse. if (!USED_PORTS.contains(port)) { ports[i++] = port; USED_PORTS.add(port); } } catch (IOException e) { throw new RuntimeException("could not open socket", e); } } // Close the sockets so that their port numbers can be used by the caller. for (ServerSocket socket : openSockets) { try { socket.close(); } catch (IOException e) { throw new RuntimeException("could not close socket", e); } } return ports; } }