Python socket.INADDR_ANY() Examples

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

You may also check out all available functions/classes of the module socket , or try the search function .

Example 1
Project: rift-python   Author: brunorijsman   File: multicast_checks.py    License: Apache License 2.0 6 votes vote down vote up
def _create_ipv4_sockets(loopback_enabled):
    # Open a multicast send socket, with IP_MULTICAST_LOOP enabled or disabled as requested.
    mcast_address = "224.0.1.195"
    port = 49501
    group = (mcast_address, port)
    txsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    txsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    if loopback_enabled:
        txsock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 1)
    else:
        txsock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 0)
    txsock.connect(group)
    # Open a multicast receive socket and join the group
    rxsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    req = struct.pack("=4sl", socket.inet_aton(mcast_address), socket.INADDR_ANY)
    rxsock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, req)
    rxsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    rxsock.bind(group)
    return (txsock, rxsock) 
Example 2
Project: ros2cli   Author: ros2   File: __init__.py    License: Apache License 2.0 6 votes vote down vote up
def receive(*, group=DEFAULT_GROUP, port=DEFAULT_PORT, timeout=None):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    try:
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        try:
            s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
        except AttributeError:
            # not available on Windows
            pass
        s.bind(('', port))

        s.settimeout(timeout)

        mreq = struct.pack('4sl', socket.inet_aton(group), socket.INADDR_ANY)
        s.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
        try:
            data, sender_addr = s.recvfrom(4096)
        finally:
            s.setsockopt(socket.IPPROTO_IP, socket.IP_DROP_MEMBERSHIP, mreq)
    finally:
        s.close()
    return data, sender_addr 
Example 3
Project: ros2cli   Author: ros2   File: hello.py    License: Apache License 2.0 6 votes vote down vote up
def __init__(self, summary_table, group=DEFAULT_GROUP, port=DEFAULT_PORT, timeout=None):
        self._dummy_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        self._socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        try:
            self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            try:
                self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
            except AttributeError:
                # not available on Windows
                pass
            self._socket.bind(('', port))

            self._socket.settimeout(timeout)

            self._mreq = struct.pack('4sl', socket.inet_aton(group), socket.INADDR_ANY)
            self._socket.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, self._mreq)
        except Exception:
            self._dummy_socket.close()
            self._socket.close()
            raise
        self._is_shutdown = False
        self._summary_table = summary_table
        self._group = group
        self._port = port 
Example 4
Project: iptvtools   Author: huxuan   File: utils.py    License: MIT License 6 votes vote down vote up
def check_udp_connectivity(url, timeout=None):
    """Check UDP connectivity."""
    ipaddr, port = url.rsplit(':', 1)
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    sock.settimeout(timeout)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
    sock.bind(('', int(port)))
    mreq = struct.pack("4sl", socket.inet_aton(ipaddr), socket.INADDR_ANY)
    sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
    try:
        if sock.recv(10240):
            return True
    except socket.timeout:
        pass
    return False 
Example 5
Project: PyXiaomiGateway   Author: Danielhiversen   File: __init__.py    License: MIT License 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 6
Project: pyShelly   Author: StyraHem   File: coap.py    License: MIT License 6 votes vote down vote up
def _init_socket(self):
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM,
                             socket.IPPROTO_UDP)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 10)
        sock.bind((self._root.bind_ip, COAP_PORT))
        if self._root.host_ip:
            mreq = struct.pack("=4s4s",
                               socket.inet_aton(COAP_IP),
                               socket.inet_aton(self._root.host_ip))
        else:
            mreq = struct.pack("=4sl",
                               socket.inet_aton(COAP_IP),
                               socket.INADDR_ANY)
        sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
        sock.settimeout(15)
        self._socket = sock 
Example 7
Project: pub   Author: tintinweb   File: poc.py    License: GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, group="239.255.255.250", port=1900):
        self.group, self.port = group, port
        self.callbacks = {}
        # multicast socket
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        logger.debug("[SSDP] bind: 0.0.0.0:%s" % port)
        sock.bind(('0.0.0.0', port))
        mreq = struct.pack("=4sl", socket.inet_aton(group), socket.INADDR_ANY)
        logger.debug("[SSDP] add membership: UDP/%s" % group)
        sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
        self.listening = False
        self.sock = sock
        self.devices = {}

    # Start listening 
Example 8
Project: script.tubecast   Author: enen92   File: ssdp.py    License: MIT License 6 votes vote down vote up
def handle_membership(self, cmd):
        if self._listen_interfaces is None:
            mreq = struct.pack(
                str("4sI"), socket.inet_aton(self._multicast_address[0]),
                socket.INADDR_ANY)
            self.socket.setsockopt(socket.IPPROTO_IP,
                                   cmd, mreq)
        else:
            for interface in self._listen_interfaces:
                try:
                    if_addr = socket.inet_aton(interface)
                except socket.error:
                    if_addr = get_interface_address(interface)
                mreq = socket.inet_aton(self._multicast_address[0]) + if_addr
                self.socket.setsockopt(socket.IPPROTO_IP,
                                       cmd, mreq) 
Example 9
Project: fluxclient   Author: flux3dp   File: discover.py    License: GNU Affero General Public License v3.0 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 10
Project: fauxmo   Author: makermusings   File: fauxmo.py    License: MIT License 6 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 
Example 11
Project: mmvt   Author: pelednoam   File: udp_listener.py    License: GNU General Public License v3.0 6 votes vote down vote up
def bind_to_multicast(port=45454, multicast_group='239.255.43.21'):
    import struct
    # Create the socket
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    # Bind to the server address
    # sock.bind((multicast_group, port))
    sock.bind(('', port))
    # Tell the operating system to add the socket to the multicast group
    # on all interfaces.
    # group = socket.inet_aton(multicast_group)
    # mreq = struct.pack('4sL', group, socket.INADDR_ANY)
    mreq = struct.pack('4sl', socket.inet_aton(multicast_group), socket.INADDR_ANY)

    sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
    return sock 
Example 12
Project: echo-pi   Author: kanesurendra   File: fauxmo.py    License: MIT License 6 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 
Example 13
Project: rift-python   Author: brunorijsman   File: udp_rx_handler.py    License: Apache License 2.0 5 votes vote down vote up
def create_socket_ipv4_rx_mcast(self):
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        except (IOError, OSError) as err:
            self.warning("Could not create IPv4 UDP socket: %s", err)
            return None
        self.enable_addr_and_port_reuse(sock)
        try:
            sock.bind((self._multicast_address, self._local_port))
        except (IOError, OSError) as err:
            self.warning("Could not bind IPv4 UDP socket to address %s port %d: %s",
                         self._multicast_address, self._local_port, err)
            return None
        if sock is None:
            return None
        if self._local_ipv4_address:
            req = struct.pack("=4s4s", socket.inet_aton(self._multicast_address),
                              socket.inet_aton(self._local_ipv4_address))
        else:
            req = struct.pack("=4sl", socket.inet_aton(self._multicast_address), socket.INADDR_ANY)
        try:
            sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, req)
        except (IOError, OSError) as err:
            self.warning("Could not join IPv4 group %s for local address %s: %s",
                         self._multicast_address, self._local_ipv4_address, err)
            return None
        if not MACOS:
            try:
                # pylint:disable=no-member
                sock.setsockopt(socket.IPPROTO_IP, socket.IP_PKTINFO, 1)
            except (IOError, OSError) as err:
                # Warn, but keep going; this socket option is not supported on macOS
                self.warning("Could not set IP_PKTINFO socket option: %s", err)
        try:
            sock.setblocking(0)
        except (IOError, OSError) as err:
            self.warning("Could set multicast receive IPv4 UDP to non-blocking mode: %s", err)
            return None
        return sock 
Example 14
Project: movistartv2xmltv   Author: ese   File: tva.py    License: GNU General Public License v2.0 5 votes vote down vote up
def getfiles(self):
        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((self.mcast_grp, self.mcast_port))
        mreq = struct.pack("=4sl", socket.inet_aton(self.mcast_grp), socket.INADDR_ANY)
        sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
        loop = True
        chunk = {}
        chunk["end"] = 0
	N = 335
        #Wait for an end chunk to start by the beginning
        while not (chunk["end"]):
            chunk = self._getchunk(sock)
            firstfile = str(chunk["filetype"])+"_"+str(chunk["fileid"])
        #Loop until firstfile
        while (loop):
                xmldata=""
                chunk = self._getchunk(sock)
                #Discard headers
                body=chunk["data"]
                while not (chunk["end"]):
                        xmldata+=body
                        chunk = self._getchunk(sock)
                        body=chunk["data"]
                #Discard last 4bytes binary footer?
                xmldata+=body[:-4]
                self._files[str(chunk["filetype"])+"_"+str(chunk["fileid"])]=xmldata
		N = N - 1
                if (str(chunk["filetype"])+"_"+str(chunk["fileid"]) == firstfile or N == 0):
                    loop = False
        sock.close() 
Example 15
Project: pulseaudio-dlna   Author: masmu   File: listener.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _multicast_struct(self, address):
        return struct.pack(
            '4sl', socket.inet_aton(address), socket.INADDR_ANY) 
Example 16
Project: genmon   Author: jgyates   File: genalexa.py    License: GNU General Public License v2.0 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 as e:
                self.LogError("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 as e:
                self.LogError('WARNING: Failed to join multicast group:'+str(e))
                ok = False

        except Exception as e:
            self.LogError("Failed to initialize UPnP sockets:"+str(e))
            return False
        if ok:
            self.LogDebug("Listening for UPnP broadcasts")

    # ---------------- upnp_broadcast_responder.fileno ------------------------- 
Example 17
Project: goodbye-mihome   Author: aluminiumgeek   File: mihome.py    License: BSD 2-Clause "Simplified" License 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)
    sock.settimeout(20)  # 2x of heartbeat period

    current = {}

    while True:
        try:
            data, _ = sock.recvfrom(SOCKET_BUFSIZE)  # buffer size is 1024 bytes
        except socket.timeout:
            continue
        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 18
Project: nightmare   Author: joxeankoret   File: cluster.py    License: GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, name, maxwidth=4, docode=False):
        self.go = True
        self.name = name
        self.width = 0
        self.maxwidth = maxwidth
        self.verbose = False
        self.docode = docode

        if docode: dcode.enableDcodeClient()

        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 19
Project: rpi3-webiopi   Author: thortex   File: coap.py    License: Apache License 2.0 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 20
Project: scoop   Author: soravux   File: minusconf.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def _multicast_join_group(sock, family, addr):
    group_bin = _inet_pton(family, addr)
    if family == socket.AF_INET: # IPv4
        mreq = group_bin + struct.pack('=I', socket.INADDR_ANY)
        sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
    elif family == socket.AF_INET6: # IPv6
        mreq = group_bin + struct.pack('@I', 0)
        sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_JOIN_GROUP, mreq)
    else:
        raise ValueError('Unsupported protocol family ' + family) 
Example 21
Project: rext   Author: j91321   File: upnp_console.py    License: GNU General Public License v3.0 5 votes vote down vote up
def initialize_sockets(self):
        try:
            # This is needed to join a multicast group
            self.mreq = struct.pack("4sl", socket.inet_aton(self.host), socket.INADDR_ANY)
            # Set up client socket
            self.csock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            self.csock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
            # 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)
            # BSD systems also need to set SO_REUSEPORT
            try:
                self.ssock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
            except Exception:
                pass

            # Only bind to this interface
            if self.interface is not None:
                print_info("Binding to interface: " + self.interface)
                self.ssock.setsockopt(socket.SOL_SOCKET, socket.SO_BINDTODEVICE,
                                      struct.pack("%ds" % (len(self.interface) + 1,), self.interface))
                self.csock.setsockopt(socket.SOL_SOCKET, socket.SO_BINDTODEVICE,
                                      struct.pack("%ds" % (len(self.interface) + 1,), self.interface))

            try:
                self.ssock.bind(('', self.port))
            except Exception:
                print_warning("failed to bind: " + self.host + ":" + str(self.port) + " ")
            try:
                self.ssock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, self.mreq)
            except Exception:
                print_warning("failed to join multicast group")
        except Exception:
            print_error("failed to initialize UPNP sockets")
            return False
        return True

    # Clean up file/socket descriptors 
Example 22
Project: aqara-mqtt   Author: monster1025   File: xiaomihub.py    License: Apache License 2.0 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 23
Project: tv_grab_es_movistartv   Author: MovistarTV   File: tv_grab_es_movistartv.py    License: GNU General Public License v3.0 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' % str(ex.args)) 
Example 24
Project: p2pool-n   Author: donSchoe   File: ipdiscover.py    License: GNU General Public License v3.0 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 25
Project: p2pool-n   Author: donSchoe   File: upnp.py    License: GNU General Public License v3.0 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: medicare-demo   Author: ofermend   File: test_socket.py    License: Apache License 2.0 5 votes vote down vote up
def testAI_PASSIVE(self):
        # Disabling this test for now; it's expectations are not portable.
        # Expected results are too dependent on system config to be made portable between systems.
        # And the only way to determine what configuration to test is to use the 
        # java.net.InetAddress.getAllByName() method, which is what is used to 
        # implement the getaddrinfo() function. Therefore, no real point in the test.
        return
        IPV4_LOOPBACK = "127.0.0.1"
        local_hostname = java.net.InetAddress.getLocalHost().getHostName()
        local_ip_address = java.net.InetAddress.getLocalHost().getHostAddress()
        for flags, host_param, expected_canonname, expected_sockaddr in [
            # First passive flag
            (socket.AI_PASSIVE, None, "", socket.INADDR_ANY),
            (socket.AI_PASSIVE, "", "", local_ip_address),
            (socket.AI_PASSIVE, "localhost", "", IPV4_LOOPBACK),
            (socket.AI_PASSIVE, local_hostname, "", local_ip_address),
            # Now passive flag AND canonname flag
            # Commenting out all AI_CANONNAME tests, results too dependent on system config
            #(socket.AI_PASSIVE|socket.AI_CANONNAME, None, "127.0.0.1", "127.0.0.1"),
            #(socket.AI_PASSIVE|socket.AI_CANONNAME, "", local_hostname, local_ip_address),
            # The following gives varying results across platforms and configurations: commenting out for now.
            # Javadoc: http://java.sun.com/j2se/1.5.0/docs/api/java/net/InetAddress.html#getCanonicalHostName()
            #(socket.AI_PASSIVE|socket.AI_CANONNAME, "localhost", local_hostname, IPV4_LOOPBACK),
            #(socket.AI_PASSIVE|socket.AI_CANONNAME, local_hostname, local_hostname, local_ip_address),
        ]:
            addrinfos = socket.getaddrinfo(host_param, 0, socket.AF_INET, socket.SOCK_STREAM, 0, flags)
            for family, socktype, proto, canonname, sockaddr in addrinfos:
                self.failUnlessEqual(expected_canonname, canonname, "For hostname '%s' and flags %d, canonname '%s' != '%s'" % (host_param, flags, expected_canonname, canonname) )
                self.failUnlessEqual(expected_sockaddr, sockaddr[0], "For hostname '%s' and flags %d, sockaddr '%s' != '%s'" % (host_param, flags, expected_sockaddr, sockaddr[0]) ) 
Example 27
Project: medicare-demo   Author: ofermend   File: test_socket.py    License: Apache License 2.0 5 votes vote down vote up
def testSpecialHostnames(self):
        for family, sock_type, flags, addr_tuple, expected in [
            ( socket.AF_INET,  None,              0,                 ("", 80),            ["localhost"]),
            ( socket.AF_INET,  None,              socket.AI_PASSIVE, ("", 80),            [socket.INADDR_ANY]),
            ( socket.AF_INET6, None,              0,                 ("", 80),            ["localhost"]),
            ( socket.AF_INET6, None,              socket.AI_PASSIVE, ("", 80),            [socket.IN6ADDR_ANY_INIT, "0:0:0:0:0:0:0:0"]),
            ( socket.AF_INET,  socket.SOCK_DGRAM, 0,                 ("<broadcast>", 80), [socket.INADDR_BROADCAST]),
            ]:
            sockaddr = socket._get_jsockaddr(addr_tuple, family, sock_type, 0, flags)
            self.failUnless(sockaddr.hostName in expected, "_get_jsockaddr returned wrong hostname '%s' for special hostname '%s'(family=%d)" % (sockaddr.hostName, addr_tuple[0], family)) 
Example 28
Project: medicare-demo   Author: ofermend   File: test_socket.py    License: Apache License 2.0 5 votes vote down vote up
def testNoneTo_get_jsockaddr(self):
        for family, flags, expected in [
            ( socket.AF_INET,  0,                 ["localhost"]),
            ( socket.AF_INET,  socket.AI_PASSIVE, [socket.INADDR_ANY]),
            ( socket.AF_INET6, 0,                 ["localhost"]),
            ( socket.AF_INET6, socket.AI_PASSIVE, [socket.IN6ADDR_ANY_INIT, "0:0:0:0:0:0:0:0"]),
            ]:
            sockaddr = socket._get_jsockaddr(None, family, None, 0, flags)
            self.failUnless(sockaddr.hostName in expected, "_get_jsockaddr returned wrong hostname '%s' for sock tuple == None (family=%d)" % (sockaddr.hostName, family)) 
Example 29
Project: odoo13-x64   Author: guohuadeng   File: mcast.py    License: GNU General Public License v3.0 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 30
Project: dubbo-python   Author: apache   File: registry.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, address, callback):
            Thread.__init__(self)
            self.multicast_group, self.multicast_port = address.split(':')
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
            # in osx we should use SO_REUSEPORT instead of SO_REUSEADDRESS
            self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
            self.sock.bind(('', int(self.multicast_port)))
            mreq = struct.pack("4sl", socket.inet_aton(self.multicast_group), socket.INADDR_ANY)
            self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
            self.callback = callback 
Example 31
Project: CTFCrackTools-V2   Author: Acmesec   File: test_socket.py    License: GNU General Public License v3.0 5 votes vote down vote up
def testAI_PASSIVE(self):
        # Disabling this test for now; it's expectations are not portable.
        # Expected results are too dependent on system config to be made portable between systems.
        # And the only way to determine what configuration to test is to use the 
        # java.net.InetAddress.getAllByName() method, which is what is used to 
        # implement the getaddrinfo() function. Therefore, no real point in the test.
        return
        IPV4_LOOPBACK = "127.0.0.1"
        local_hostname = java.net.InetAddress.getLocalHost().getHostName()
        local_ip_address = java.net.InetAddress.getLocalHost().getHostAddress()
        for flags, host_param, expected_canonname, expected_sockaddr in [
            # First passive flag
            (socket.AI_PASSIVE, None, "", socket.INADDR_ANY),
            (socket.AI_PASSIVE, "", "", local_ip_address),
            (socket.AI_PASSIVE, "localhost", "", IPV4_LOOPBACK),
            (socket.AI_PASSIVE, local_hostname, "", local_ip_address),
            # Now passive flag AND canonname flag
            # Commenting out all AI_CANONNAME tests, results too dependent on system config
            #(socket.AI_PASSIVE|socket.AI_CANONNAME, None, "127.0.0.1", "127.0.0.1"),
            #(socket.AI_PASSIVE|socket.AI_CANONNAME, "", local_hostname, local_ip_address),
            # The following gives varying results across platforms and configurations: commenting out for now.
            # Javadoc: http://java.sun.com/j2se/1.5.0/docs/api/java/net/InetAddress.html#getCanonicalHostName()
            #(socket.AI_PASSIVE|socket.AI_CANONNAME, "localhost", local_hostname, IPV4_LOOPBACK),
            #(socket.AI_PASSIVE|socket.AI_CANONNAME, local_hostname, local_hostname, local_ip_address),
        ]:
            addrinfos = socket.getaddrinfo(host_param, 0, socket.AF_INET, socket.SOCK_STREAM, 0, flags)
            for family, socktype, proto, canonname, sockaddr in addrinfos:
                self.failUnlessEqual(expected_canonname, canonname, "For hostname '%s' and flags %d, canonname '%s' != '%s'" % (host_param, flags, expected_canonname, canonname) )
                self.failUnlessEqual(expected_sockaddr, sockaddr[0], "For hostname '%s' and flags %d, sockaddr '%s' != '%s'" % (host_param, flags, expected_sockaddr, sockaddr[0]) ) 
Example 32
Project: CTFCrackTools-V2   Author: Acmesec   File: test_socket.py    License: GNU General Public License v3.0 5 votes vote down vote up
def testSpecialHostnames(self):
        for family, sock_type, flags, addr_tuple, expected in [
            ( socket.AF_INET,  0,                 0,                 ("", 80),            ["localhost"]),
            ( socket.AF_INET,  0,                 socket.AI_PASSIVE, ("", 80),            [socket.INADDR_ANY]),
            ( socket.AF_INET6, 0,                 0,                 ("", 80),            ["localhost"]),
            ( socket.AF_INET6, 0,                 socket.AI_PASSIVE, ("", 80),            [socket.IN6ADDR_ANY_INIT, "0:0:0:0:0:0:0:0"]),
            ( socket.AF_INET,  socket.SOCK_DGRAM, 0,                 ("<broadcast>", 80), ["broadcasthost"]),
            ]:
            sockaddr = socket._get_jsockaddr(addr_tuple, family, sock_type, 0, flags)
            self.failUnless(sockaddr.hostName in expected, "_get_jsockaddr returned wrong hostname '%s' for special hostname '%s'(family=%d)" % (sockaddr.hostName, addr_tuple[0], family)) 
Example 33
Project: CTFCrackTools-V2   Author: Acmesec   File: test_socket.py    License: GNU General Public License v3.0 5 votes vote down vote up
def testNoneTo_get_jsockaddr(self):
        for family, flags, expected in [
            ( socket.AF_INET,  0,                 ["localhost"]),
            ( socket.AF_INET,  socket.AI_PASSIVE, [socket.INADDR_ANY]),
            ( socket.AF_INET6, 0,                 ["localhost"]),
            ( socket.AF_INET6, socket.AI_PASSIVE, [socket.IN6ADDR_ANY_INIT, "0:0:0:0:0:0:0:0"]),
            ]:
            sockaddr = socket._get_jsockaddr(None, family, 0, 0, flags)
            self.failUnless(sockaddr.hostName in expected, "_get_jsockaddr returned wrong hostname '%s' for sock tuple == None (family=%d)" % (sockaddr.hostName, family)) 
Example 34
Project: mitmcanary   Author: cylance   File: dns.py    License: GNU General Public License v3.0 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 35
Project: WaveSync   Author: blaa   File: receiver.py    License: MIT License 5 votes vote down vote up
def connection_made(self, transport):
        "Configure multicast"
        sock = transport.get_extra_info('socket')
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        # Check if address is multicast and join group.
        group, port = self.channel

        multicast = True
        octets = group.split('.')

        # Received audio chunk counter
        self.chunk_queue.init_queue()

        if len(octets) != 4:
            multicast = False
        else:
            try:
                octet_0 = int(octets[0])
                if not 224 <= octet_0 <= 239:
                    multicast = False
            except ValueError:
                multicast = False

        # If not multicast - end
        if multicast is False:
            print("Assuming unicast reception on %s:%d" % (group, port))
            return

        # Multicast - join group
        print("Joining multicast group", group)

        group = socket.inet_aton(group)
        mreq = struct.pack('4sL', group, socket.INADDR_ANY)
        sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq) 
Example 36
Project: android_universal   Author: bkerler   File: mcast.py    License: MIT License 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 37
Project: crazyswarm   Author: USC-ACTLab   File: udp_multicast.py    License: MIT License 5 votes vote down vote up
def __init__(self, MCAST_GRP = '224.1.1.1', MCAST_PORT = 5007):
    self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    self.sock.bind(('', MCAST_PORT))  # use MCAST_GRP instead of '' to listen only
                                 # to MCAST_GRP, not all groups on MCAST_PORT
    mreq = struct.pack("4sl", socket.inet_aton(MCAST_GRP), socket.INADDR_ANY)
    self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq) 
Example 38
Project: CTFCrackTools   Author: Acmesec   File: test_socket.py    License: GNU General Public License v3.0 5 votes vote down vote up
def testAI_PASSIVE(self):
        # Disabling this test for now; it's expectations are not portable.
        # Expected results are too dependent on system config to be made portable between systems.
        # And the only way to determine what configuration to test is to use the 
        # java.net.InetAddress.getAllByName() method, which is what is used to 
        # implement the getaddrinfo() function. Therefore, no real point in the test.
        return
        IPV4_LOOPBACK = "127.0.0.1"
        local_hostname = java.net.InetAddress.getLocalHost().getHostName()
        local_ip_address = java.net.InetAddress.getLocalHost().getHostAddress()
        for flags, host_param, expected_canonname, expected_sockaddr in [
            # First passive flag
            (socket.AI_PASSIVE, None, "", socket.INADDR_ANY),
            (socket.AI_PASSIVE, "", "", local_ip_address),
            (socket.AI_PASSIVE, "localhost", "", IPV4_LOOPBACK),
            (socket.AI_PASSIVE, local_hostname, "", local_ip_address),
            # Now passive flag AND canonname flag
            # Commenting out all AI_CANONNAME tests, results too dependent on system config
            #(socket.AI_PASSIVE|socket.AI_CANONNAME, None, "127.0.0.1", "127.0.0.1"),
            #(socket.AI_PASSIVE|socket.AI_CANONNAME, "", local_hostname, local_ip_address),
            # The following gives varying results across platforms and configurations: commenting out for now.
            # Javadoc: http://java.sun.com/j2se/1.5.0/docs/api/java/net/InetAddress.html#getCanonicalHostName()
            #(socket.AI_PASSIVE|socket.AI_CANONNAME, "localhost", local_hostname, IPV4_LOOPBACK),
            #(socket.AI_PASSIVE|socket.AI_CANONNAME, local_hostname, local_hostname, local_ip_address),
        ]:
            addrinfos = socket.getaddrinfo(host_param, 0, socket.AF_INET, socket.SOCK_STREAM, 0, flags)
            for family, socktype, proto, canonname, sockaddr in addrinfos:
                self.failUnlessEqual(expected_canonname, canonname, "For hostname '%s' and flags %d, canonname '%s' != '%s'" % (host_param, flags, expected_canonname, canonname) )
                self.failUnlessEqual(expected_sockaddr, sockaddr[0], "For hostname '%s' and flags %d, sockaddr '%s' != '%s'" % (host_param, flags, expected_sockaddr, sockaddr[0]) ) 
Example 39
Project: CTFCrackTools   Author: Acmesec   File: test_socket.py    License: GNU General Public License v3.0 5 votes vote down vote up
def testSpecialHostnames(self):
        for family, sock_type, flags, addr_tuple, expected in [
            ( socket.AF_INET,  0,                 0,                 ("", 80),            ["localhost"]),
            ( socket.AF_INET,  0,                 socket.AI_PASSIVE, ("", 80),            [socket.INADDR_ANY]),
            ( socket.AF_INET6, 0,                 0,                 ("", 80),            ["localhost"]),
            ( socket.AF_INET6, 0,                 socket.AI_PASSIVE, ("", 80),            [socket.IN6ADDR_ANY_INIT, "0:0:0:0:0:0:0:0"]),
            ( socket.AF_INET,  socket.SOCK_DGRAM, 0,                 ("<broadcast>", 80), ["broadcasthost"]),
            ]:
            sockaddr = socket._get_jsockaddr(addr_tuple, family, sock_type, 0, flags)
            self.failUnless(sockaddr.hostName in expected, "_get_jsockaddr returned wrong hostname '%s' for special hostname '%s'(family=%d)" % (sockaddr.hostName, addr_tuple[0], family)) 
Example 40
Project: CTFCrackTools   Author: Acmesec   File: test_socket.py    License: GNU General Public License v3.0 5 votes vote down vote up
def testNoneTo_get_jsockaddr(self):
        for family, flags, expected in [
            ( socket.AF_INET,  0,                 ["localhost"]),
            ( socket.AF_INET,  socket.AI_PASSIVE, [socket.INADDR_ANY]),
            ( socket.AF_INET6, 0,                 ["localhost"]),
            ( socket.AF_INET6, socket.AI_PASSIVE, [socket.IN6ADDR_ANY_INIT, "0:0:0:0:0:0:0:0"]),
            ]:
            sockaddr = socket._get_jsockaddr(None, family, 0, 0, flags)
            self.failUnless(sockaddr.hostName in expected, "_get_jsockaddr returned wrong hostname '%s' for sock tuple == None (family=%d)" % (sockaddr.hostName, family)) 
Example 41
Project: p2ptv-pi   Author: alesnav   File: Multicast.py    License: MIT License 4 votes vote down vote up
def _joinMulticast(self, addr, port, sock):
        import struct
        for res in socket.getaddrinfo(addr, port, socket.AF_UNSPEC, socket.SOCK_DGRAM):
            af, socktype, proto, canonname, sa = res
            break

        if af == socket.AF_INET6:
            num_colons = addr.count(':')
            new_colons = ':'
            for i in range(num_colons, 8):
                new_colons = '%s0:' % new_colons

            addr = addr.replace('::', new_colons)
            addr_pack = ''
            for l in addr.split(':'):
                word = int(l, 16)
                addr_pack = addr_pack + struct.pack('!H', word)

            interfaces = []
            for i in range(1, 32):
                try:
                    mreq = addr_pack + struct.pack('l', i)
                    sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_JOIN_GROUP, mreq)
                    ok = True
                    self.log.debug('Joined IPv6 multicast on interface %d' % i)
                    interfaces.append(i)
                except Exception as e:
                    pass

            if len(interfaces) == 0:
                self.log.fatal('Could not join on any interface')
                raise Exception('Could not join multicast on any interface')
            return interfaces
        if af == socket.AF_INET:
            addr_pack = ''
            grpaddr = 0
            bytes = map(int, string.split(addr, '.'))
            for byte in bytes:
                grpaddr = grpaddr << 8 | byte

            ifaddr = socket.INADDR_ANY
            mreq = struct.pack('ll', socket.htonl(grpaddr), socket.htonl(ifaddr))
            try:
                self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
            except Exception as e:
                self.log.exception('Exception joining IPv4 multicast')

            return [] 
Example 42
Project: BitTorrent   Author: kenorb-contrib   File: NatTraversal.py    License: GNU General Public License v3.0 4 votes vote down vote up
def begin_discovery(self):
        # bind to an available port, and join the multicast group
        df = get_deferred_host_ip()
        yield df
        hostip = df.getResult()
        
        for p in xrange(self.upnp_addr[1], self.upnp_addr[1]+50):
            try:
                # Original RawServer cannot do this!
                s = self.rawserver.create_multicastsocket(p, hostip)
                self.transport = s
                self.rawserver.start_listening_multicast(s, self)
                df = s.listening_port.joinGroup(self.upnp_addr[0],
                                                socket.INADDR_ANY)
                yield df
                result = df.getResult()
                # blargh
                if twisted.copyright.version >= '2.4.0':
                    success = None
                    # ACKKKK..K. Prevents "Unhandled error in Deferred"
                    if df._debugInfo is not None:
                        df._debugInfo.failResult = None
                else:
                    success = 1
                if result is success:
                    break
                elif isinstance(result, twisted.python.failure.Failure):
                    # HACK.  If the failure contains a 'No such device' error
                    # then we abort the discovery because this error denotes
                    # that the peer is not connected to the network.
                    if hasattr( result.value, "__getitem__" ) and \
                       result.value[2] == 19:
                        yield 0   # abort discovery.      
                else:
                    # I suppose keep trying on different ports, but why would
                    # joinGroup fail?
                    self.transport = None
                    x = s.listening_port.stopListening()
                    if isinstance(x, defer.Deferred):
                        yield x
                        x.getResult()
            except socket.error, e:
                # may look weird, but spin the event loop once on failure
                yield defer.succeed(True) 
Example 43
Project: openhtf   Author: google   File: multicast.py    License: Apache License 2.0 4 votes vote down vote up
def run(self):
    """Listen for pings until stopped."""
    self._live = True
    self._sock.settimeout(self.LISTEN_TIMEOUT_S)

    # Passing in INADDR_ANY means the kernel will choose the default interface.
    # The localhost address is used to receive messages sent in "local_only"
    # mode and the default address is used to receive all other messages.
    for interface_ip in (socket.INADDR_ANY, LOCALHOST_ADDRESS):
      self._sock.setsockopt(
          socket.IPPROTO_IP,
          socket.IP_ADD_MEMBERSHIP,
          # IP_ADD_MEMBERSHIP takes the 8-byte group address followed by the IP
          # assigned to the interface on which to listen.
          struct.pack('!4sL', socket.inet_aton(self.address), interface_ip))

    if sys.platform == 'darwin':
      self._sock.setsockopt(socket.SOL_SOCKET,
                            socket.SO_REUSEPORT,
                            1)  # Allow multiple listeners to bind.
    else:
      self._sock.setsockopt(socket.SOL_SOCKET,
                            socket.SO_REUSEADDR,
                            1)  # Allow multiple listeners to bind.
    self._sock.bind((self.address, self.port))

    while self._live:
      try:
        data, address = self._sock.recvfrom(MAX_MESSAGE_BYTES)
        data = data.decode('utf-8')
        log_line = 'Received multicast message from %s: %s' % (address, data)
        response = self._callback(data)
        if response is not None:
          log_line += ', responding with %s bytes' % len(response)
          # Send replies out-of-band instead of with the same multicast socket
          # so that multiple processes on the same host can listen for
          # requests and reply (if they all try to use the multicast socket
          # to reply, they conflict and this sendto fails).
          response = response.encode('utf-8')
          socket.socket(socket.AF_INET, socket.SOCK_DGRAM).sendto(
              response, address)
        _LOG.debug(log_line)
      except socket.timeout:
        pass
      except socket.error:
        _LOG.debug('Error receiving multicast message', exc_info=True)