code: public static int findFreePort() throws IOException {
          ServerSocket socket = null;
  
          try {
              socket = new ServerSocket(0);
  
              return socket.getLocalPort();
          } finally {
              if (socket != null) {
                  socket.close();
              }
          }
      }
docs: Find a free port on the test system to be used by the servlet engine
  
  @return the socket number
  @throws IOException in case of I/O failure