def _port_not_in_use ( ) : s = socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) port = 0 s . bind ( ( '' , port ) ) _ , port = s . getsockname ( ) return port
stack overflow python port scanner
Use the port 0 trick to find a port not in use .
def _port_not_in_use():
    """Use the port 0 trick to find a port not in use."""
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    port = 0
    s.bind(('', port))
    _, port = s.getsockname()
    return port