code: public static int findUnusedPort() throws IOException
      {
          int port;
  
          try (ServerSocket socket = new ServerSocket()) {
              socket.bind(new InetSocketAddress(0));
              port = socket.getLocalPort();
          }
  
          return port;
      }
docs: Find an unused port.