def get_unused_localhost_port():
 usock = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)
 usock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
 usock.bind(('127.0.0.1', 0))
 port = usock.getsockname()[1]
 if (port in (54505, 54506, 64505, 64506, 64510, 64511, 64520, 64521)):
  port = get_unused_localhost_port()
  usock.close()
  return port
 DARWIN = (True if sys.platform.startswith('darwin') else False)
 BSD = (True if ('bsd' in sys.platform) else False)
 if (DARWIN and (port in _RUNTESTS_PORTS)):
  port = get_unused_localhost_port()
  usock.close()
  return port
 _RUNTESTS_PORTS[port] = usock
 if (DARWIN or BSD):
  usock.close()
 return port

def get_unused_localhost_port ( ) : usock = socket . socket ( family = socket . AF_INET , type = socket . SOCK_STREAM ) usock . setsockopt ( socket . SOL_SOCKET , socket . SO_REUSEADDR , 1 ) usock . bind ( ( '127.0.0.1' , 0 ) ) port = usock . getsockname ( ) [ 1 ] if ( port in ( 54505 , 54506 , 64505 , 64506 , 64510 , 64511 , 64520 , 64521 ) ) : port = get_unused_localhost_port ( ) usock . close ( ) return port DARWIN = ( True if sys . platform . startswith ( 'darwin' ) else False ) BSD = ( True if ( 'bsd' in sys . platform ) else False ) if ( DARWIN and ( port in _RUNTESTS_PORTS ) ) : port = get_unused_localhost_port ( ) usock . close ( ) return port _RUNTESTS_PORTS [ port ] = usock if ( DARWIN or BSD ) : usock . close ( ) return port
return a random unused port on localhost .