Allocate an unused port.

    There is a small race condition here (between the time we allocate the
    port, and the time it actually gets used), but for the purposes for which
    this function gets used it isn't a problem in practice.

def allocate_port():
    """Allocate an unused port.

    There is a small race condition here (between the time we allocate the
    port, and the time it actually gets used), but for the purposes for which
    this function gets used it isn't a problem in practice.
    """
    sock = socket.socket()
    try:
        sock.bind(("localhost", 0))
        return get_port(sock)
    finally:
        sock.close()