code: public static com.sun.net.httpserver.HttpServer bind(InetAddress address, int startPort, int maxPort) {
          com.sun.net.httpserver.HttpServer aServer = createServer();
          int port = -1;
          for (int possiblePort = startPort; port == -1 && possiblePort <= maxPort; possiblePort++) {
              try {
                  InetSocketAddress s = new InetSocketAddress(address, possiblePort);
                  aServer.bind(s, 1);
                  port = possiblePort;
              } catch (IOException e) {
                  // try next number
                  continue;
              }
          }
          if (aServer.getAddress() == null) {
              throw new RuntimeException(new BindException("Unable to bind to: " + address.getHostAddress()));
          }
          return aServer;
      }
docs: Finds free port number and binds a server to it.
  @param address   address to listen on.
  @param startPort lowest allowed port.
  @param maxPort   highest (inclusive) port.
  @return server created.