code: def pick_free_port(hostname=REDIRECT_HOST, port=0):
      
      import socket
      s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
      try:
          s.bind((hostname, port))  # port=0 finds an open port
      except OSError as e:
          log.warning("Could not bind to %s:%s %s", hostname, port, e)
          if port == 0:
              print('Unable to find an open port for authentication.')
              raise AuthenticationException(e)
          else:
              return pick_free_port(hostname, 0)
      addr, port = s.getsockname()
      s.close()
      return port
docs: Try to bind a port. Default=0 selects a free port.