def find_open_port() -> int:
    """
    Find a random open port on local host.
    """
    import socket

    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
        # Passes 0 means find any open port.
        # See https://stackoverflow.com/questions/1365265/on-localhost-how-do-i-pick-a-free-port-number
        sock.bind(("", 0))
        return sock.getsockname()[1]
Find a random open port on local host.
allennlp/common/util.py