Python socket.INADDR_ANY() Examples

The following are code examples for showing how to use socket.INADDR_ANY(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the ones you don't like. You can also save this page to your account.

Example 1
Project: homeassistant   Author: lazcad   File: xiaomi.py    (license) View Source Project 6 votes vote down vote up
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 
Example 2
Project: vivisect-py3   Author: bat-serjo   File: devent.py    (license) View Source Project 6 votes vote down vote up
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() 
Example 3
Project: TrackBots   Author: RoboCupULaval   File: vision_receiver.py    (license) View Source Project 6 votes vote down vote up
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) 
Example 4
Project: flux_line_bot   Author: blesscat   File: discover.py    (license) View Source Project 6 votes vote down vote up
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) 
Example 5
Project: vagus   Author: privacore   File: UDPMulticastHandler.py    (license) View Source Project 6 votes vote down vote up
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 
Example 6
Project: PyXiaomiGateway   Author: Danielhiversen   File: __init__.py    (license) View Source Project 6 votes vote down vote up
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 
Example 7
Project: hmv-s16   Author: cmuphyscomp   File: optirx.py    (BSD 3-Clause "New" or "Revised" License) View Source Project 5 votes vote down vote up
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 
Example 8
Project: pyaqara   Author: javefang   File: protocol.py    (license) View Source Project 5 votes vote down vote up
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") 
Example 9
Project: p2pool-bch   Author: amarian12   File: upnp.py    (license) View Source Project 5 votes vote down vote up
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 
Example 10
Project: p2pool-bch   Author: amarian12   File: ipdiscover.py    (license) View Source Project 5 votes vote down vote up
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) 
Example 11
Project: panonoctl   Author: florianl   File: ssdp.py    (license) View Source Project 5 votes vote down vote up
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) 
Example 12
Project: goodbye-mihome   Author: aluminiumgeek   File: mihome.py    (license) View Source Project 5 votes vote down vote up
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()) 
Example 13
Project: Legion   Author: MooseDojo   File: multicast.py    (license) View Source Project 5 votes vote down vote up
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]) 
Example 14
Project: rpi3-webiopi   Author: thortex   File: coap.py    (license) View Source Project 5 votes vote down vote up
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)) 
Example 15
Project: p2pool-unitus   Author: amarian12   File: upnp.py    (license) View Source Project 5 votes vote down vote up
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 
Example 16
Project: p2pool-unitus   Author: amarian12   File: ipdiscover.py    (license) View Source Project 5 votes vote down vote up
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) 
Example 17
Project: aqara-mqtt   Author: monster1025   File: xiaomihub.py    (license) View Source Project 5 votes vote down vote up
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 
Example 18
Project: mitmcanary   Author: CylanceSPEAR   File: dns.py    (license) View Source Project 5 votes vote down vote up
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 
Example 19
Project: tv_grab_es_movistartv   Author: MovistarTV   File: tv_grab_es_movistartv.py    (license) View Source Project 5 votes vote down vote up
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) 
Example 20
Project: p2pool-dgb-sha256   Author: ilsawa   File: upnp.py    (license) View Source Project 5 votes vote down vote up
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 
Example 21
Project: p2pool-dgb-sha256   Author: ilsawa   File: ipdiscover.py    (license) View Source Project 5 votes vote down vote up
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) 
Example 22
Project: python2-tracer   Author: extremecoders-re   File: mcast.py    (license) View Source Project 5 votes vote down vote up
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)) 
Example 23
Project: vivisect-py3   Author: bat-serjo   File: cluster.py    (license) View Source Project 5 votes vote down vote up
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) 
Example 24
Project: mppt_config   Author: dilithiumpower   File: can_ethernet.py    (license) View Source Project 5 votes vote down vote up
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) 
Example 25
Project: p2pool-ltc   Author: ilsawa   File: upnp.py    (license) View Source Project 5 votes vote down vote up
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 
Example 26
Project: p2pool-ltc   Author: ilsawa   File: ipdiscover.py    (license) View Source Project 5 votes vote down vote up
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) 
Example 27
Project: p2pool-bsty   Author: amarian12   File: upnp.py    (license) View Source Project 5 votes vote down vote up
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 
Example 28
Project: p2pool-bsty   Author: amarian12   File: ipdiscover.py    (license) View Source Project 5 votes vote down vote up
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) 
Example 29
Project: p2pool-cann   Author: ilsawa   File: upnp.py    (license) View Source Project 5 votes vote down vote up
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 
Example 30
Project: p2pool-cann   Author: ilsawa   File: ipdiscover.py    (license) View Source Project 5 votes vote down vote up
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) 
Example 31
Project: pcars   Author: jamesremuscat   File: stream.py    (license) View Source Project 5 votes vote down vote up
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) 
Example 32
Project: internetdostrem   Author: luisleao   File: fauxmo.py    (license) View Source Project 5 votes vote down vote up
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") 
Example 33
Project: IOT-Pi3-Alexa-Automation   Author: nassir-malik   File: fauxmo.py    (license) View Source Project 5 votes vote down vote up
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") 
Example 34
Project: mdcs   Author: CtrlC-Root   File: server.py    (license) View Source Project 5 votes vote down vote up
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 
Example 35
Project: SalamiPi   Author: developer8987   File: fauxmo.py    (license) View Source Project 5 votes vote down vote up
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") 
Example 36
Project: pyimc   Author: oysstu   File: udp.py    (license) View Source Project 4 votes vote down vote up
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