def find_unused_port():
 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 try:
  sock.bind(('127.0.0.1', 0))
  sock.listen(socket.SOMAXCONN)
  (_, port) = sock.getsockname()
 finally:
  sock.close()
 return port

def find_unused_port ( ) : sock = socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) try : sock . bind ( ( '127.0.0.1' , 0 ) ) sock . listen ( socket . SOMAXCONN ) ( _ , port ) = sock . getsockname ( ) finally : sock . close ( ) return port
returns an unused port that should be suitable for binding .