https://github.com/thom311/libnl/blob/libnl3_2_25/lib/socket.c#L63.

def generate_local_port():
    """https://github.com/thom311/libnl/blob/libnl3_2_25/lib/socket.c#L63."""
    global _PREVIOUS_LOCAL_PORT
    if _PREVIOUS_LOCAL_PORT is None:
        try:
            with contextlib.closing(socket.socket(getattr(socket, 'AF_NETLINK', -1), socket.SOCK_RAW)) as s:
                s.bind((0, 0))
                _PREVIOUS_LOCAL_PORT = int(s.getsockname()[0])
        except OSError:
            _PREVIOUS_LOCAL_PORT = 4294967295  # UINT32_MAX
    return int(_PREVIOUS_LOCAL_PORT)