def findFreePort(interface='127.0.0.1', family=socket.AF_INET,
                 type=socket.SOCK_STREAM):
    """
    Ask the platform to allocate a free port on the specified interface, then
    release the socket and return the address which was allocated.

    @param interface: The local address to try to bind the port on.
    @type interface: C{str}

    @param type: The socket type which will use the resulting port.

    @return: A two-tuple of address and port, like that returned by
        L{socket.getsockname}.
    """
    addr = socket.getaddrinfo(interface, 0)[0][4]
    probe = socket.socket(family, type)
    try:
        probe.bind(addr)
        if family == socket.AF_INET6:
            sockname = probe.getsockname()
            hostname = socket.getnameinfo(
                sockname, socket.NI_NUMERICHOST | socket.NI_NUMERICSERV)[0]
            return (hostname, sockname[1])
        else:
            return probe.getsockname()
    finally:
        probe.close()

    Ask the platform to allocate a free port on the specified interface, then
    release the socket and return the address which was allocated.

    @param interface: The local address to try to bind the port on.
    @type interface: C{str}

    @param type: The socket type which will use the resulting port.

    @return: A two-tuple of address and port, like that returned by
        L{socket.getsockname}.
    
stackoverflow/venv/lib/python3.6/site-packages/twisted/internet/test/connectionmixins.py