code: public static int getRandomPort() {
      try {
        ServerSocket socket = new ServerSocket(0);
        try {
          return socket.getLocalPort();
        } finally {
          socket.close();
        }
      } catch (IOException e) {
        return -1;
      }
    }
docs: Find a random free port in localhost for binding.
  @return A port number or -1 for failure.