Python socket 模块,INADDR_ANY 实例源码

我们从Python开源项目中,提取了以下36个代码示例,用于说明如何使用socket.INADDR_ANY

项目:homeassistant    作者:lazcad    | 项目源码 | 文件源码
def _create_mcast_socket(self):
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        if self._interface != 'any':
            if platform.system() != "Windows":
                sock.bind((self.MULTICAST_ADDRESS, self.MULTICAST_PORT))
            else:
                sock.bind((self._interface, self.MULTICAST_PORT))

            mreq = socket.inet_aton(self.MULTICAST_ADDRESS) + socket.inet_aton(self._interface)
        else:
            sock.bind((self.MULTICAST_ADDRESS, self.MULTICAST_PORT))
            mreq = struct.pack("4sl", socket.inet_aton(self.MULTICAST_ADDRESS), socket.INADDR_ANY)

        sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
        return sock
项目:vivisect-py3    作者:bat-serjo    | 项目源码 | 文件源码
def setEventCast(self, mcast='224.56.56.56', port=45654, bind='0.0.0.0'):
        '''
        Tie this CobraEventCore to any others which share the same multicast
        ip and port.  This basically creates a ( udp "unreliable" ) "bus" on
        which events are serialized using json.
        '''
        # Setup a UDP casting socket
        self._ce_mcastport = port
        self._ce_mcasthost = mcast
        self._ce_ecastsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self._ce_ecastsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self._ce_ecastsock.bind((bind,port))

        # Join the multicast IP
        mreq = struct.pack("4sL", socket.inet_aton(mcast), socket.INADDR_ANY)
        self._ce_ecastsock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)

        thr = threading.Thread(target=self._runSocketListener)
        thr.setDaemon(True)
        thr.start()
项目:TrackBots    作者:RoboCupULaval    | 项目源码 | 文件源码
def __init__(self, server_address):

        self.server_address = server_address

        self.logger = logging.getLogger('VisionReceiver')

        self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.socket.bind(server_address)

        if ip_address(server_address[0]).is_multicast:
            self.socket.setsockopt(socket.IPPROTO_IP,
                                   socket.IP_ADD_MEMBERSHIP,
                                   struct.pack("=4sl", socket.inet_aton(server_address[0]), socket.INADDR_ANY))

        self.field = Field()
        self._detection_frame_queue = queue.Queue()

        self._thread = threading.Thread(target=self.receive_packet, daemon=True)
项目:flux_line_bot    作者:blesscat    | 项目源码 | 文件源码
def create_sockets(mcst_ipaddr, mcst_port):
        mreq = struct.pack("4sl", socket.inet_aton(mcst_ipaddr),
                           socket.INADDR_ANY)

        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM,
                          socket.IPPROTO_UDP)
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        s.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)

        if platform.system() == "Windows":
            s.bind(("", mcst_port))
            return (s, )

        else:
            s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
            s.bind((mcst_ipaddr, mcst_port))

            bsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM,
                                  socket.IPPROTO_UDP)
            bsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            bsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
            bsock.bind(("", 1901))

            return (s, bsock)
项目:vagus    作者:privacore    | 项目源码 | 文件源码
def setup_ipv4_multicast_socket(ifaddrs, if_name, addr):
    #todo: if_name ignored
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind(("", Config.udp_multicast.port))

    s.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, Config.udp_multicast.ttl)
    s.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 0)

    mreq = struct.pack("4sl", socket.inet_aton(addr), socket.INADDR_ANY)

    s.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)

    s.setblocking(0)

    multicast_socket_ipv4.append((s,addr))

    return True
项目:PyXiaomiGateway    作者:Danielhiversen    | 项目源码 | 文件源码
def _create_mcast_socket(self):
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        if self._interface != 'any':
            if platform.system() != "Windows":
                sock.bind((self.MULTICAST_ADDRESS, self.MULTICAST_PORT))
            else:
                sock.bind((self._interface, self.MULTICAST_PORT))

            mreq = socket.inet_aton(self.MULTICAST_ADDRESS) + socket.inet_aton(self._interface)
        else:
            if platform.system() != "Windows":
                sock.bind((self.MULTICAST_ADDRESS, self.MULTICAST_PORT))
            else:
                sock.bind(('', self.MULTICAST_PORT))
            mreq = struct.pack("4sl", socket.inet_aton(self.MULTICAST_ADDRESS), socket.INADDR_ANY)

        sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
        return sock
项目:hmv-s16    作者:cmuphyscomp    | 项目源码 | 文件源码
def mkdatasock(ip_address=None, multicast_address=MULTICAST_ADDRESS, port=PORT_DATA):
    "Create a data socket."
    ip_address = gethostip() if not ip_address else ip_address
    datasock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0)
    datasock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    datasock.bind((ip_address, port))
    # join a multicast group
    mreq = struct.pack("=4sl", socket.inet_aton(multicast_address), socket.INADDR_ANY)
    datasock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
    datasock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, SOCKET_BUFSIZE)
    return datasock
项目:pyaqara    作者:javefang    | 项目源码 | 文件源码
def _add_membership(self):
        """private: add multicast membership"""
        _LOGGER.debug("Joining multicast group...")
        sock = self.transport.get_extra_info("socket")
        group = socket.inet_aton(MCAST_ADDR)
        mreq = struct.pack("4sL", group, socket.INADDR_ANY)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        _LOGGER.debug("Multicast membership added")
项目:p2pool-bch    作者:amarian12    | 项目源码 | 文件源码
def search_device(self):
        """
        Triggers a UPnP device discovery.

        The returned deferred will be called with the L{UPnPDevice} that has
        been found in the LAN.

        @return: A deferred called with the detected L{UPnPDevice} instance.
        @rtype: L{twisted.internet.defer.Deferred}
        """
        if self._discovery is not None:
            raise ValueError('already used')
        self._discovery = defer.Deferred()
        self._discovery_timeout = reactor.callLater(6, self._on_discovery_timeout)

        attempt = 0
        mcast = None
        while True:
            try:
                self.mcast = reactor.listenMulticast(1900+attempt, self)
                break
            except CannotListenError:
                attempt = random.randint(0, 500)

        # joined multicast group, starting upnp search
        self.mcast.joinGroup('239.255.255.250', socket.INADDR_ANY)

        self.transport.write(_UPNP_SEARCH_REQUEST, (_UPNP_MCAST, _UPNP_PORT))
        self.transport.write(_UPNP_SEARCH_REQUEST, (_UPNP_MCAST, _UPNP_PORT))
        self.transport.write(_UPNP_SEARCH_REQUEST, (_UPNP_MCAST, _UPNP_PORT))

        return self._discovery

    #Private methods
项目:p2pool-bch    作者:amarian12    | 项目源码 | 文件源码
def _discover_multicast():
    """
    Local IP discovery protocol via multicast:
        - Broadcast 3 ping multicast packet with "ping" in it
        - Wait for an answer
        - Retrieve the ip address from the returning packet, which is ours
    """

    nonce = str(random.randrange(2**64))
    p = _LocalNetworkMulticast(nonce)

    for attempt in itertools.count():
        port = 11000 + random.randint(0, 5000)
        try:
            mcast = reactor.listenMulticast(port, p)
        except CannotListenError:
            if attempt >= 10:
                raise
            continue
        else:
            break

    try:
        yield mcast.joinGroup('239.255.255.250', socket.INADDR_ANY)

        logging.debug("Sending multicast ping")
        for i in xrange(3):
            p.transport.write(nonce, ('239.255.255.250', port))

        address, = yield p.address_received.get_deferred(5)
    finally:
        mcast.stopListening()

    defer.returnValue(address)
项目:panonoctl    作者:florianl    | 项目源码 | 文件源码
def discover(self):
        ws      = None
        usn     = None
        apiV    = None
        srv     = None
        req =  ('M-SEARCH * HTTP/1.1\r\n' +
                'MX: 10\r\n' +
                'HOST: 239.255.255.250:1900\r\n' +
                'MAN: \"ssdp:discover\"\r\n' +
                'NT: panono:ball-camera\r\n' +
                '\r\n')
        ws = None
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        sock.settimeout(7)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
        mcast = struct.pack('4sL', socket.inet_aton('239.255.255.250') , socket.INADDR_ANY)
        sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mcast)
        sock.bind(('', 1900))
        try:
            sock.sendto( req.encode(), ('239.255.255.250', 1900))
        except socket.error as e:
            print(e)
            return (None, None, None)
        for _ in range(5):
            try:
                data, addr = sock.recvfrom(1024)
                if not data: continue
                ws = ssdpNotify().getLocation(data)
                if ws is None: continue
                usn = ssdpNotify().getUsn(data)
                apiV = ssdpNotify().getApiVersion(data)
                srv = ssdpNotify().getSrv(data)
                break
            except socket.error as e:
                print(e)
                break
        sock.close()
        return (ws, usn, apiV, srv)
项目:goodbye-mihome    作者:aluminiumgeek    | 项目源码 | 文件源码
def receiver(service='mihome'):
    from plugins import gateway

    assert service in MULTICAST, 'No such service'
    store = get_store()
    address, port = MULTICAST.get(service)
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.bind(("0.0.0.0", port))

    mreq = struct.pack("=4sl", socket.inet_aton(address), socket.INADDR_ANY)
    sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 32)
    sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 1)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, SOCKET_BUFSIZE)
    sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)

    current = {}

    while True:
        data, _ = sock.recvfrom(SOCKET_BUFSIZE)  # buffer size is 1024 bytes
        print(datetime.now().isoformat(), data)
        if service == 'mihome':
            message = json.loads(data.decode())
            data = json.loads(message['data'])
            if message.get('model') in ('sensor_ht', 'weather.v1') and not sensor_ht.process(conn, cursor, current, message, data):
                continue
            elif message.get('model') == 'magnet':
                magnet.process(store, message, data)
            elif message.get('model') == 'gateway':
                gateway.process(store, message, data)
            current = {}
        elif service == 'yeelight':
            yeelight.process(data.decode())
项目:Legion    作者:MooseDojo    | 项目源码 | 文件源码
def recv(self, callback):
        # Look up multicast group address in name server and find out IP version
        addrinfo = socket.getaddrinfo(self.group, None)[0]

        # Create a socket
        s = socket.socket(addrinfo[0], socket.SOCK_DGRAM)

        # Allow multiple copies of this program on one machine
        # (not strictly needed)
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        # Bind it to the port
        s.bind(('', self.port))

        group_bin = socket.inet_pton(addrinfo[0], addrinfo[4][0])
        # Join group
        if addrinfo[0] == socket.AF_INET: # IPv4
            mreq = group_bin + struct.pack('=I', socket.INADDR_ANY)
            s.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)

        # Loop, printing any data we receive
        while True:
            if callback == None:
                return
            data, sender = s.recvfrom(1500)
            data = data.decode()
            while data[-1:] == '\0': data = data[:-1] # Strip trailing \0's
            #callback(sender, data.split(':'))
            callback.put([sender, data])
项目:rpi3-webiopi    作者:thortex    | 项目源码 | 文件源码
def enableMulticast(self):
        while not self.running:
            pass
        mreq = struct.pack("4sl", socket.inet_aton(self.multicast_ip), socket.INADDR_ANY)
        self.socket.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
        info("CoAP Server binded on coap://%s:%s/ (MULTICAST)" % (self.multicast_ip, self.port))
项目:p2pool-unitus    作者:amarian12    | 项目源码 | 文件源码
def search_device(self):
        """
        Triggers a UPnP device discovery.

        The returned deferred will be called with the L{UPnPDevice} that has
        been found in the LAN.

        @return: A deferred called with the detected L{UPnPDevice} instance.
        @rtype: L{twisted.internet.defer.Deferred}
        """
        if self._discovery is not None:
            raise ValueError('already used')
        self._discovery = defer.Deferred()
        self._discovery_timeout = reactor.callLater(6, self._on_discovery_timeout)

        attempt = 0
        mcast = None
        while True:
            try:
                self.mcast = reactor.listenMulticast(1900+attempt, self)
                break
            except CannotListenError:
                attempt = random.randint(0, 500)

        # joined multicast group, starting upnp search
        self.mcast.joinGroup('239.255.255.250', socket.INADDR_ANY)

        self.transport.write(_UPNP_SEARCH_REQUEST, (_UPNP_MCAST, _UPNP_PORT))
        self.transport.write(_UPNP_SEARCH_REQUEST, (_UPNP_MCAST, _UPNP_PORT))
        self.transport.write(_UPNP_SEARCH_REQUEST, (_UPNP_MCAST, _UPNP_PORT))

        return self._discovery

    #Private methods
项目:p2pool-unitus    作者:amarian12    | 项目源码 | 文件源码
def _discover_multicast():
    """
    Local IP discovery protocol via multicast:
        - Broadcast 3 ping multicast packet with "ping" in it
        - Wait for an answer
        - Retrieve the ip address from the returning packet, which is ours
    """

    nonce = str(random.randrange(2**64))
    p = _LocalNetworkMulticast(nonce)

    for attempt in itertools.count():
        port = 11000 + random.randint(0, 5000)
        try:
            mcast = reactor.listenMulticast(port, p)
        except CannotListenError:
            if attempt >= 10:
                raise
            continue
        else:
            break

    try:
        yield mcast.joinGroup('239.255.255.250', socket.INADDR_ANY)

        logging.debug("Sending multicast ping")
        for i in xrange(3):
            p.transport.write(nonce, ('239.255.255.250', port))

        address, = yield p.address_received.get_deferred(5)
    finally:
        mcast.stopListening()

    defer.returnValue(address)
项目:aqara-mqtt    作者:monster1025    | 项目源码 | 文件源码
def _create_mcast_socket(self):
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.bind((self.MULTICAST_ADDRESS, self.MULTICAST_PORT))
        mreq = struct.pack("4sl", socket.inet_aton(self.MULTICAST_ADDRESS), socket.INADDR_ANY)
        sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
        return sock
项目:mitmcanary    作者:CylanceSPEAR    | 项目源码 | 文件源码
def get_mdns_sock(self):
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        if sys.platform == 'darwin':
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
        sock.bind(('', 5353))

        mreq = struct.pack("4sl", socket.inet_aton('224.0.0.251'), socket.INADDR_ANY)
        sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)

        return sock
项目:tv_grab_es_movistartv    作者:MovistarTV    | 项目源码 | 文件源码
def __get_xml_files(self, mc_grp, mc_port):
        try:
            loop = True
            chunk = {"end": 0}
            max_files = 1000
            _files = {}
            first_file = ''
            logger.debug('Descargando XML de %s:%s' % (mc_grp, mc_port))
            sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            sock.settimeout(3)
            sock.bind((mc_grp, int(mc_port)))
            mreq = struct.pack("=4sl", socket.inet_aton(mc_grp), socket.INADDR_ANY)
            sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
            # Wait for an end chunk to start by the beginning
            while not (chunk["end"]):
                chunk = self.__parse_chunk(sock.recv(1500))
                first_file = str(chunk["filetype"]) + "_" + str(chunk["fileid"])
            # Loop until firstfile
            while loop:
                xmldata = ""
                chunk = self.__parse_chunk(sock.recv(1500))
                # Discard headers
                body = chunk["data"]
                while not (chunk["end"]):
                    xmldata += body
                    chunk = self.__parse_chunk(sock.recv(1500))
                    body = chunk["data"]
                # Discard last 4bytes binary footer?
                xmldata += body[:-4]
                _files[str(chunk["filetype"]) + "_" + str(chunk["fileid"])] = xmldata
                logger.debug('XML: %s_%s' % (chunk["filetype"], chunk["fileid"]))
                max_files -= 1
                if str(chunk["filetype"]) + "_" + str(chunk["fileid"]) == first_file or max_files == 0:
                    loop = False
            sock.close()
            return _files
        except Exception, ex:
            logger.error('Error al descargar los archivos XML: %s' % ex.args)
项目:p2pool-dgb-sha256    作者:ilsawa    | 项目源码 | 文件源码
def search_device(self):
        """
        Triggers a UPnP device discovery.

        The returned deferred will be called with the L{UPnPDevice} that has
        been found in the LAN.

        @return: A deferred called with the detected L{UPnPDevice} instance.
        @rtype: L{twisted.internet.defer.Deferred}
        """
        if self._discovery is not None:
            raise ValueError('already used')
        self._discovery = defer.Deferred()
        self._discovery_timeout = reactor.callLater(6, self._on_discovery_timeout)

        attempt = 0
        mcast = None
        while True:
            try:
                self.mcast = reactor.listenMulticast(1900+attempt, self)
                break
            except CannotListenError:
                attempt = random.randint(0, 500)

        # joined multicast group, starting upnp search
        self.mcast.joinGroup('239.255.255.250', socket.INADDR_ANY)

        self.transport.write(_UPNP_SEARCH_REQUEST, (_UPNP_MCAST, _UPNP_PORT))
        self.transport.write(_UPNP_SEARCH_REQUEST, (_UPNP_MCAST, _UPNP_PORT))
        self.transport.write(_UPNP_SEARCH_REQUEST, (_UPNP_MCAST, _UPNP_PORT))

        return self._discovery

    #Private methods
项目:p2pool-dgb-sha256    作者:ilsawa    | 项目源码 | 文件源码
def _discover_multicast():
    """
    Local IP discovery protocol via multicast:
        - Broadcast 3 ping multicast packet with "ping" in it
        - Wait for an answer
        - Retrieve the ip address from the returning packet, which is ours
    """

    nonce = str(random.randrange(2**64))
    p = _LocalNetworkMulticast(nonce)

    for attempt in itertools.count():
        port = 11000 + random.randint(0, 5000)
        try:
            mcast = reactor.listenMulticast(port, p)
        except CannotListenError:
            if attempt >= 10:
                raise
            continue
        else:
            break

    try:
        yield mcast.joinGroup('239.255.255.250', socket.INADDR_ANY)

        logging.debug("Sending multicast ping")
        for i in xrange(3):
            p.transport.write(nonce, ('239.255.255.250', port))

        address, = yield p.address_received.get_deferred(5)
    finally:
        mcast.stopListening()

    defer.returnValue(address)
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
def receiver(group):
    # Look up multicast group address in name server and find out IP version
    addrinfo = socket.getaddrinfo(group, None)[0]

    # Create a socket
    s = socket.socket(addrinfo[0], socket.SOCK_DGRAM)

    # Allow multiple copies of this program on one machine
    # (not strictly needed)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    # Bind it to the port
    s.bind(('', MYPORT))

    group_bin = socket.inet_pton(addrinfo[0], addrinfo[4][0])
    # Join group
    if addrinfo[0] == socket.AF_INET: # IPv4
        mreq = group_bin + struct.pack('=I', socket.INADDR_ANY)
        s.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
    else:
        mreq = group_bin + struct.pack('@I', 0)
        s.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_JOIN_GROUP, mreq)

    # Loop, printing any data we receive
    while True:
        data, sender = s.recvfrom(1500)
        while data[-1:] == '\0': data = data[:-1] # Strip trailing \0's
        print (str(sender) + '  ' + repr(data))
项目:vivisect-py3    作者:bat-serjo    | 项目源码 | 文件源码
def __init__(self, name, maxwidth=multiprocessing.cpu_count(), docode=False):
        self.go = True
        self.name = name
        self.width = 0
        self.maxwidth = maxwidth
        self.verbose = False
        self.docode = docode

        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.sock.bind(("",cluster_port))
        mreq = struct.pack("4sL", socket.inet_aton(cluster_ip), socket.INADDR_ANY)
        self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
项目:mppt_config    作者:dilithiumpower    | 项目源码 | 文件源码
def Connect(self):
    self.socket_mode = UDP_MODE
    self.mac = uuid.getnode()

    # Set up UDP receiver.
    self.udp_rx_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    self.udp_rx_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    # Pack multicast group structure correctly.
    mreq = struct.pack('=4sl', socket.inet_aton(MCAST_GRP),socket.INADDR_ANY) 

    # Request access to multicast group.
    self.udp_rx_sock.setsockopt(socket.IPPROTO_IP,
                                socket.IP_ADD_MEMBERSHIP, mreq)  

    # Bind to all intfs.
    self.udp_rx_sock.bind(('', MCAST_PORT))
    self.udp_rx_sock.settimeout(TIMEOUT)

    # Set up UDP transmitter.
    self.udp_tx_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    self.udp_tx_sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 255)

    # Get the MAC address of the local adapter.
    msg = bytearray(8)
    struct.pack_into('<Q', msg, 0, int(self.mac))
    self.local_mac = ''.join('{:02x}'.format(x) for x in msg[0:6])
    logging.debug('MAC Addr: %s', self.local_mac)
项目:p2pool-ltc    作者:ilsawa    | 项目源码 | 文件源码
def search_device(self):
        """
        Triggers a UPnP device discovery.

        The returned deferred will be called with the L{UPnPDevice} that has
        been found in the LAN.

        @return: A deferred called with the detected L{UPnPDevice} instance.
        @rtype: L{twisted.internet.defer.Deferred}
        """
        if self._discovery is not None:
            raise ValueError('already used')
        self._discovery = defer.Deferred()
        self._discovery_timeout = reactor.callLater(6, self._on_discovery_timeout)

        attempt = 0
        mcast = None
        while True:
            try:
                self.mcast = reactor.listenMulticast(1900+attempt, self)
                break
            except CannotListenError:
                attempt = random.randint(0, 500)

        # joined multicast group, starting upnp search
        self.mcast.joinGroup('239.255.255.250', socket.INADDR_ANY)

        self.transport.write(_UPNP_SEARCH_REQUEST, (_UPNP_MCAST, _UPNP_PORT))
        self.transport.write(_UPNP_SEARCH_REQUEST, (_UPNP_MCAST, _UPNP_PORT))
        self.transport.write(_UPNP_SEARCH_REQUEST, (_UPNP_MCAST, _UPNP_PORT))

        return self._discovery

    #Private methods
项目:p2pool-ltc    作者:ilsawa    | 项目源码 | 文件源码
def _discover_multicast():
    """
    Local IP discovery protocol via multicast:
        - Broadcast 3 ping multicast packet with "ping" in it
        - Wait for an answer
        - Retrieve the ip address from the returning packet, which is ours
    """

    nonce = str(random.randrange(2**64))
    p = _LocalNetworkMulticast(nonce)

    for attempt in itertools.count():
        port = 11000 + random.randint(0, 5000)
        try:
            mcast = reactor.listenMulticast(port, p)
        except CannotListenError:
            if attempt >= 10:
                raise
            continue
        else:
            break

    try:
        yield mcast.joinGroup('239.255.255.250', socket.INADDR_ANY)

        logging.debug("Sending multicast ping")
        for i in xrange(3):
            p.transport.write(nonce, ('239.255.255.250', port))

        address, = yield p.address_received.get_deferred(5)
    finally:
        mcast.stopListening()

    defer.returnValue(address)
项目:p2pool-bsty    作者:amarian12    | 项目源码 | 文件源码
def search_device(self):
        """
        Triggers a UPnP device discovery.

        The returned deferred will be called with the L{UPnPDevice} that has
        been found in the LAN.

        @return: A deferred called with the detected L{UPnPDevice} instance.
        @rtype: L{twisted.internet.defer.Deferred}
        """
        if self._discovery is not None:
            raise ValueError('already used')
        self._discovery = defer.Deferred()
        self._discovery_timeout = reactor.callLater(6, self._on_discovery_timeout)

        attempt = 0
        mcast = None
        while True:
            try:
                self.mcast = reactor.listenMulticast(1900+attempt, self)
                break
            except CannotListenError:
                attempt = random.randint(0, 500)

        # joined multicast group, starting upnp search
        self.mcast.joinGroup('239.255.255.250', socket.INADDR_ANY)

        self.transport.write(_UPNP_SEARCH_REQUEST, (_UPNP_MCAST, _UPNP_PORT))
        self.transport.write(_UPNP_SEARCH_REQUEST, (_UPNP_MCAST, _UPNP_PORT))
        self.transport.write(_UPNP_SEARCH_REQUEST, (_UPNP_MCAST, _UPNP_PORT))

        return self._discovery

    #Private methods
项目:p2pool-bsty    作者:amarian12    | 项目源码 | 文件源码
def _discover_multicast():
    """
    Local IP discovery protocol via multicast:
        - Broadcast 3 ping multicast packet with "ping" in it
        - Wait for an answer
        - Retrieve the ip address from the returning packet, which is ours
    """

    nonce = str(random.randrange(2**64))
    p = _LocalNetworkMulticast(nonce)

    for attempt in itertools.count():
        port = 11000 + random.randint(0, 5000)
        try:
            mcast = reactor.listenMulticast(port, p)
        except CannotListenError:
            if attempt >= 10:
                raise
            continue
        else:
            break

    try:
        yield mcast.joinGroup('239.255.255.250', socket.INADDR_ANY)

        logging.debug("Sending multicast ping")
        for i in xrange(3):
            p.transport.write(nonce, ('239.255.255.250', port))

        address, = yield p.address_received.get_deferred(5)
    finally:
        mcast.stopListening()

    defer.returnValue(address)
项目:p2pool-cann    作者:ilsawa    | 项目源码 | 文件源码
def search_device(self):
        """
        Triggers a UPnP device discovery.

        The returned deferred will be called with the L{UPnPDevice} that has
        been found in the LAN.

        @return: A deferred called with the detected L{UPnPDevice} instance.
        @rtype: L{twisted.internet.defer.Deferred}
        """
        if self._discovery is not None:
            raise ValueError('already used')
        self._discovery = defer.Deferred()
        self._discovery_timeout = reactor.callLater(6, self._on_discovery_timeout)

        attempt = 0
        mcast = None
        while True:
            try:
                self.mcast = reactor.listenMulticast(1900+attempt, self)
                break
            except CannotListenError:
                attempt = random.randint(0, 500)

        # joined multicast group, starting upnp search
        self.mcast.joinGroup('239.255.255.250', socket.INADDR_ANY)

        self.transport.write(_UPNP_SEARCH_REQUEST, (_UPNP_MCAST, _UPNP_PORT))
        self.transport.write(_UPNP_SEARCH_REQUEST, (_UPNP_MCAST, _UPNP_PORT))
        self.transport.write(_UPNP_SEARCH_REQUEST, (_UPNP_MCAST, _UPNP_PORT))

        return self._discovery

    #Private methods
项目:p2pool-cann    作者:ilsawa    | 项目源码 | 文件源码
def _discover_multicast():
    """
    Local IP discovery protocol via multicast:
        - Broadcast 3 ping multicast packet with "ping" in it
        - Wait for an answer
        - Retrieve the ip address from the returning packet, which is ours
    """

    nonce = str(random.randrange(2**64))
    p = _LocalNetworkMulticast(nonce)

    for attempt in itertools.count():
        port = 11000 + random.randint(0, 5000)
        try:
            mcast = reactor.listenMulticast(port, p)
        except CannotListenError:
            if attempt >= 10:
                raise
            continue
        else:
            break

    try:
        yield mcast.joinGroup('239.255.255.250', socket.INADDR_ANY)

        logging.debug("Sending multicast ping")
        for i in xrange(3):
            p.transport.write(nonce, ('239.255.255.250', port))

        address, = yield p.address_received.get_deferred(5)
    finally:
        mcast.stopListening()

    defer.returnValue(address)
项目:pcars    作者:jamesremuscat    | 项目源码 | 文件源码
def run(self):
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

        # Bind to the server address
        sock.bind(("", self.port))
        group = socket.inet_aton(_MCAST_ANY)
        mreq = struct.pack("4sL", group, socket.INADDR_ANY)
        sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)

        while True:
            data = sock.recv(1400)
            packet = Packet.readFrom(BytesIO(data))
            for listener in self.listeners:
                listener.handlePacket(packet)
项目:internetdostrem    作者:luisleao    | 项目源码 | 文件源码
def init_socket(self):
        ok = True
        self.ip = '239.255.255.250'
        self.port = 1900
        try:
            #This is needed to join a multicast group
            self.mreq = struct.pack("4sl",socket.inet_aton(self.ip),socket.INADDR_ANY)

            #Set up server socket
            self.ssock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM,socket.IPPROTO_UDP)
            self.ssock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)

            try:
                self.ssock.bind(('',self.port))
            except Exception, e:
                dbg("WARNING: Failed to bind %s:%d: %s" , (self.ip,self.port,e))
                ok = False

            try:
                self.ssock.setsockopt(socket.IPPROTO_IP,socket.IP_ADD_MEMBERSHIP,self.mreq)
            except Exception, e:
                dbg('WARNING: Failed to join multicast group:',e)
                ok = False

        except Exception, e:
            dbg("Failed to initialize UPnP sockets:",e)
            return False
        if ok:
            dbg("Listening for UPnP broadcasts")
项目:IOT-Pi3-Alexa-Automation    作者:nassir-malik    | 项目源码 | 文件源码
def init_socket(self):
        ok = True
        self.ip = '239.255.255.250'
        self.port = 1900
        try:
            #This is needed to join a multicast group
            self.mreq = struct.pack("4sl",socket.inet_aton(self.ip),socket.INADDR_ANY)

            #Set up server socket
            self.ssock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM,socket.IPPROTO_UDP)
            self.ssock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)

            try:
                self.ssock.bind(('',self.port))
            except Exception:
                dbg("WARNING: Failed to bind %s:%d: %s" , (self.ip,self.port))
                ok = False

            try:
                self.ssock.setsockopt(socket.IPPROTO_IP,socket.IP_ADD_MEMBERSHIP,self.mreq)
            except Exception:
                dbg('WARNING: Failed to join multicast group:')
                ok = False

        except Exception:
            dbg("Failed to initialize UPnP sockets:")
            return False
        if ok:
            dbg("Listening for UPnP broadcasts")
项目:mdcs    作者:CtrlC-Root    | 项目源码 | 文件源码
def __init__(self, node, host, port, group):
        super().__init__((host, port), NodeMulticastRequestHandler, bind_and_activate=False)
        self.allow_reuse_address = True # XXX should be an option?
        self._group = group

        # create the group membership request
        self._group_member = struct.pack('4sL', socket.inet_aton(self._group), socket.INADDR_ANY)

        # store the server settings
        self.node = node
项目:SalamiPi    作者:developer8987    | 项目源码 | 文件源码
def init_socket(self):
        ok = True
        self.ip = '239.255.255.250'
        self.port = 1900
        try:
            #This is needed to join a multicast group
            self.mreq = struct.pack("4sl",socket.inet_aton(self.ip),socket.INADDR_ANY)

            #Set up server socket
            self.ssock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM,socket.IPPROTO_UDP)
            self.ssock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)

            try:
                self.ssock.bind(('',self.port))
            except Exception, e:
                dbg("WARNING: Failed to bind %s:%d: %s" , (self.ip,self.port,e))
                ok = False

            try:
                self.ssock.setsockopt(socket.IPPROTO_IP,socket.IP_ADD_MEMBERSHIP,self.mreq)
            except Exception, e:
                dbg('WARNING: Failed to join multicast group:',e)
                ok = False

        except Exception, e:
            dbg("Failed to initialize UPnP sockets:",e)
            return False
        if ok:
            dbg("Listening for UPnP broadcasts")
项目:pyimc    作者:oysstu    | 项目源码 | 文件源码
def get_multicast_socket(sock=None):
    if not sock:
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

    sock.settimeout(0.001)

    # set multicast interface to any local interface
    sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_IF, socket.inet_aton('0.0.0.0'))

    # Enable multicast, TTL should be <32 (local network)
    sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 5)

    # Allow reuse of addresses
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    # Allow receiving multicast broadcasts (subscribe to multicast group)
    try:
        mreq = struct.pack('4sL', socket.inet_aton(multicast_ip), socket.INADDR_ANY)
        sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)

        # Do not loop back own messages
        sock.setsockopt(socket.SOL_IP, socket.IP_MULTICAST_LOOP, 0)
    except OSError as e:
        logger.error('Unable to obtain socket with multicast enabled.')
        raise e

    port = None
    for i in range(30100, 30105):
        try:
            # Binding to 0.0.0.0 results in multiple messages if there is multiple interfaces available
            # Kept as-is to avoid losing messages
            sock.bind(('0.0.0.0', i))
            port = i
            break
        except OSError as e:
            # Socket already in use without SO_REUSEADDR enabled
            continue

    if not port:
        raise RuntimeError('No IMC multicast ports free on local interface.')

    return sock