public static int findAvailablePort(String portRange) throws IOException {
    // ':' is the default value which means no constraints on the portRange
    if (StringUtils.isBlank(portRange) || portRange.equals(":")) {
      try (ServerSocket socket = new ServerSocket(0)) {
        return socket.getLocalPort();
      } catch (IOException e) {
        throw new IOException("Failed to allocate a automatic port", e);
      }
    }
    // valid user registered port https://en.wikipedia.org/wiki/Registered_port
    int start = 1024;
    int end = 65535;
    String[] ports = portRange.split(":", -1);
    if (!ports[0].isEmpty()) {
      start = Integer.parseInt(ports[0]);
    }
    if (!ports[1].isEmpty()) {
      end = Integer.parseInt(ports[1]);
    }
    for (int i = start; i <= end; ++i) {
      try (ServerSocket socket = new ServerSocket(i)) {
        return socket.getLocalPort();
      } catch (IOException e) {
        // ignore this
      }
    }
    throw new IOException("No available port in the portRange: " + portRange);
  }
@Test
  void testfindAvailablePort() throws IOException {
    assertTrue(RemoteInterpreterUtils.findAvailablePort(":") > 0);

    String portRange = ":30000";
    assertTrue(RemoteInterpreterUtils.findAvailablePort(portRange) <= 30000);

    portRange = "30000:";
    assertTrue(RemoteInterpreterUtils.findAvailablePort(portRange) >= 30000);

    portRange = "30000:40000";
    int port = RemoteInterpreterUtils.findAvailablePort(portRange);
    assertTrue(port >= 30000 && port <= 40000);
  }