0001
0002
0003
0004
0005
0006
0007
0008
0009
0010
0011
0012
0013
0014
0015
0016
0017
0018 package org.apache.hadoop.net;
0019
0020 import org.slf4j.Logger;
0021 import org.slf4j.LoggerFactory;
0022
0023 import java.io.IOException;
0024 import java.net.ServerSocket;
0025 import java.util.Random;
0026
0027
0028
0029
0030
0031
0032 public class ServerSocketUtil {
0033
0034 private static final Logger LOG = LoggerFactory.getLogger(ServerSocketUtil.class);
0035 private static Random rand = new Random();
0036
0037
0038
0039
0040
0041
0042
0043
0044
0045 public static int getPort(int port, int retries) throws IOException {
0046 int tryPort = port;
0047 int tries = 0;
0048 while (true) {
0049 if (tries > 0 || tryPort == 0) {
0050 tryPort = port + rand.nextInt(65535 - port);
0051 }
0052 if (tryPort == 0) {
0053 continue;
0054 }
0055 try (ServerSocket s = new ServerSocket(tryPort)) {
0056 LOG.info("Using port " + tryPort);
0057 return tryPort;
0058 } catch (IOException e) {
0059 tries++;
0060 if (tries >= retries) {
0061 LOG.info("Port is already in use; giving up");
0062 throw e;
0063 } else {
0064 LOG.info("Port is already in use; trying again");
0065 }
0066 }
0067 }
0068 }
0069
0070
0071
0072
0073
0074
0075
0076 private static boolean isPortAvailable(int port) {
0077 try (ServerSocket s = new ServerSocket(port)) {
0078 return true;
0079 } catch (IOException e) {
0080 return false;
0081 }
0082 }
0083
0084
0085
0086
0087
0088
0089
0090
0091
0092
0093 public static int waitForPort(int port, int retries)
0094 throws InterruptedException, IOException {
0095 int tries = 0;
0096 while (true) {
0097 if (isPortAvailable(port)) {
0098 return port;
0099 } else {
0100 tries++;
0101 if (tries >= retries) {
0102 throw new IOException(
0103 "Port is already in use; giving up after " + tries + " times.");
0104 }
0105 Thread.sleep(1000);
0106 }
0107 }
0108 }
0109
0110
0111
0112
0113
0114
0115
0116
0117
0118
0119 public static int[] getPorts(int numPorts) throws IOException {
0120 ServerSocket[] sockets = new ServerSocket[numPorts];
0121 int[] ports = new int[numPorts];
0122 for (int i = 0; i < numPorts; i++) {
0123 ServerSocket sock = new ServerSocket(0);
0124 sockets[i] = sock;
0125 ports[i] = sock.getLocalPort();
0126 }
0127 for (ServerSocket sock : sockets) {
0128 sock.close();
0129 }
0130 return ports;
0131 }
0132 }