Python socket.IP_ADD_MEMBERSHIP() Examples

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

Example 1
Project: rift-python   Author: brunorijsman   File: multicast_checks.py    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: dockerizeme   Author: dockerizeme   File: snippet.py    Apache License 2.0 6 votes vote down vote up
def server(timeout=5):

    socket.setdefaulttimeout(timeout)

    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, 2)
    sock.bind(('', MCAST_PORT))

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

    cond = gobject.IO_IN | gobject.IO_HUP
    gobject.io_add_watch(sock, cond, handle_requests)

    gtk.main() 
Example 3
Project: ros2cli   Author: ros2   File: __init__.py    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 4
Project: kohorte   Author: mct   File: lpd.py    GNU General Public License v2.0 6 votes vote down vote up
def open_socket(self):
        if self.sock:
            print timestamp(), self, "Double call to open_socket()?  self.sock ==", repr(self.sock)
            return

        if time.time() - self.last_sock_attempt < self.sock_attempt_time:
            return
        self.last_sock_attempt = time.time()

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

        try:
            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_LOOP, 1)
            sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL,  1)
            sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_IF, socket.INADDR_ANY)
            sock.bind((config.mcast_grp, config.mcast_port))
            sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
        except socket.error as e:
            print timestamp(), self, "Error opening socket, will try again later:", e
        else:
            self.sock = sock
            self.last_announce = 0
            print timestamp(), self, "Listening" 
Example 5
Project: yeelib   Author: codingjoe   File: discover.py    Apache License 2.0 6 votes vote down vote up
def connection_made(self, transport):
        self.transport = transport
        ucast_socket = transport.get_extra_info('socket')
        try:
            ucast_socket.bind(('', MCAST_PORT))
            fcntl.fcntl(ucast_socket, fcntl.F_SETFL, os.O_NONBLOCK)
            group = socket.inet_aton(
                SimpleServiceDiscoveryProtocol.MULTICAST_ADDRESS)
            mreq = struct.pack("4sl", group, socket.INADDR_ANY)
            ucast_socket.setsockopt(
                socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
        except socket.error as e:
            ucast_socket.close()
            self.connection_lost(exc=e)
        else:
            self.bcast_msg_task = asyncio.Task(send_search_broadcast(transport)) 
Example 6
Project: crap   Author: wittrup   File: startup.py    MIT License 6 votes vote down vote up
def __init__(self, IP, PORT, SOCK_TYPE, PROTO):
        self.sock = socket.socket(socket.AF_INET, SOCK_TYPE, PROTO)  # Internet
        self.address = (IP, PORT)
        self.dase = b''
        if PROTO == socket.IPPROTO_UDP:  # if multicast
            self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            if IP:
                self.mreq = struct.pack("4sl", socket.inet_aton(IP), socket.INADDR_ANY)
                self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, self.mreq)
            self.sock.bind(('', PORT))
        else:  # UDP and TCP
            self.sock.bind((IP, PORT))
        self.sock_type = SOCK_TYPE
        if SOCK_TYPE == socket.SOCK_STREAM:  # TCP
            self.sock.listen()
            self.clients = []
        super(listenthread, self).__init__()
        self._stop = threading.Event() 
Example 7
Project: pymediaroom   Author: dgomes   File: notify.py    MIT License 6 votes vote down vote up
def create_socket():
    # Create multicast socket
    addrinfo = socket.getaddrinfo(MEDIAROOM_BROADCAST_ADDR, None)[0]
    sock = socket.socket(addrinfo[0], socket.SOCK_DGRAM)
    sock.settimeout(0)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    # for BSD/Darwin only
    try:
        socket.SO_REUSEPORT
    except AttributeError:
        _LOGGER.debug("No SO_REUSEPORT available, skipping")
    else:
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)

    # IGMP packet
    group_bin = socket.inet_pton(addrinfo[0], addrinfo[4][0])
    mreq = group_bin + struct.pack('=I', socket.INADDR_ANY)
    sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)

    sock.bind(('', MEDIAROOM_BROADCAST_PORT))

    return sock 
Example 8
Project: flux_line_bot   Author: blesscat   File: discover.py    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 9
Project: Static-UPnP   Author: nigelb   File: util.py    GNU General Public License v2.0 6 votes vote down vote up
def setup_sockets(self):

    self.sockets = {}
    ip_addresses = get_interface_addresses(self.logger)

    self.ip_addresses = ip_addresses

    multi_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    multi_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    multi_sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, self.ttl)

    for ip in ip_addresses:
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        mreq=socket.inet_aton(self.address)+socket.inet_aton(ip)
        multi_sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
        self.logger.info("Regestering multicast for: %s: %s"%(self.address, ip))
        sock.bind((ip, self.port))

        self.sockets[ip] = sock

    multi_sock.bind(("", self.port))
    self.socks = [self.sockets[x] for x in self.sockets.keys()]
    self.multi_sock = multi_sock 
Example 10
Project: WSD-python   Author: roncapat   File: wsd_discovery__operations.py    GNU General Public License v3.0 6 votes vote down vote up
def open_multicast_udp_socket(addr: str, port: int) -> socket.socket:
    res = socket.getaddrinfo(addr, port, type=socket.SOCK_DGRAM)

    if not res:
        raise ConnectionError

    addrinfo = res[0]

    sock = socket.socket(addrinfo[0], socket.SOCK_DGRAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.bind(('', port))
    gbin = socket.inet_pton(addrinfo[0], addrinfo[4][0])
    if addrinfo[0] == socket.AF_INET:
        mreq = gbin + struct.pack('=I', socket.INADDR_ANY)
        sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
    else:
        mreq = gbin + struct.pack('@I', 0)
        sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_JOIN_GROUP, mreq)

    return sock 
Example 11
Project: fluxclient   Author: flux3dp   File: discover.py    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 12
Project: pymiio   Author: pauln   File: DevAPI.py    GNU General Public License v3.0 6 votes vote down vote up
def connect(self):
		local = self.getLocalIp()
		print("Local IP:", local)
		self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
		self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
		self.socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_IF, socket.inet_aton(local))
		self.socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)

		request = socket.inet_aton(MULTICAST_ADDRESS) + socket.inet_aton(local)
		self.socket.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, request)

		bindTo = local
		if sys.platform.startswith("darwin") or sys.platform.startswith("linux"):
			bindTo = '0.0.0.0'
		
		self.socket.bind((bindTo, MULTICAST_BIND_PORT))

		self.connected = True

		print("Connected to Dev API") 
Example 13
Project: multicast-relay   Author: alsmith   File: multicast-relay.py    GNU General Public License v3.0 5 votes vote down vote up
def addListener(self, addr, port, service):
        if self.isBroadcast(addr):
            self.etherAddrs[addr] = self.broadcastIpToMac(addr)
        elif self.isMulticast(addr):
            self.etherAddrs[addr] = self.multicastIpToMac(addr)
        else:
            # unicast -- we don't know yet which IP we'll want to send to
            self.etherAddrs[addr] = None

        # Set up the receiving socket and corresponding IP and interface information.
        # One receiving socket is required per multicast address.
        rx = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_UDP)
        rx.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        for interface in self.interfaces:
            (ifname, mac, ip, netmask) = self.getInterface(interface)

            # Add this interface to the receiving socket's list.
            if self.isBroadcast(addr):
                rx.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
            elif self.isMulticast(addr):
                packedAddress = struct.pack('4s4s', socket.inet_aton(addr), socket.inet_aton(ip))
                rx.setsockopt(socket.SOL_IP, socket.IP_ADD_MEMBERSHIP, packedAddress)

            # Generate a transmitter socket. Each interface
            # requires its own transmitting socket.
            tx = socket.socket(socket.AF_PACKET, socket.SOCK_RAW)
            tx.bind((ifname, 0))

            self.transmitters.append({'relay': {'addr': addr, 'port': port}, 'interface': ifname, 'addr': ip, 'mac': mac, 'netmask': netmask, 'socket': tx, 'service': service})

        rx.bind((addr, port))
        self.receivers.append(rx) 
Example 14
Project: rift-python   Author: brunorijsman   File: udp_rx_handler.py    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)
        return sock 
Example 15
Project: NiujiaoDebugger   Author: MrSrc   File: mcast.py    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 16
Project: mppt_config   Author: dilithiumpower   File: can_ethernet.py    MIT License 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 17
Project: goodbye-mihome   Author: aluminiumgeek   File: mihome.py    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: evil-ssdp   Author: initstring   File: evil_ssdp.py    MIT License 5 votes vote down vote up
def __init__(self, local_ip, local_port, analyze):
        self.sock = None
        self.known_hosts = []
        self.local_ip = local_ip
        self.local_port = local_port
        self.analyze_mode = analyze
        ssdp_port = 1900  # Defined by SSDP spec, do not change
        mcast_group = '239.255.255.250'  # Defined by SSDP spec, do not change
        server_address = ('', ssdp_port)

        # The re below can help us identify obviously false requests
        # from detection tools.
        self.valid_st = re.compile(r'^[a-zA-Z0-9.\-_]+:[a-zA-Z0-9.\-_:]+$')

        # Generating a new unique USD/UUID may help prevent signature-like
        # detection tools.
        self.session_usn = ('uuid:'
                            + self.gen_random(8) + '-'
                            + self.gen_random(4) + '-'
                            + self.gen_random(4) + '-'
                            + self.gen_random(4) + '-'
                            + self.gen_random(12))

        # Create the socket
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        # Bind to the server address
        self.sock.bind(server_address)

        # Tell the operating system to add the socket to
        # the multicast group on for the interface on the specific IP.
        group = socket.inet_aton(mcast_group)
        mreq = struct.pack('4s4s', group, socket.inet_aton(self.local_ip))
        self.sock.setsockopt(
            socket.IPPROTO_IP,
            socket.IP_ADD_MEMBERSHIP,
            mreq) 
Example 19
Project: multiremote   Author: mrworf   File: ssdp.py    GNU General Public License v2.0 5 votes vote down vote up
def _initSSDP(self):
    logging.info('Init SSDP')
    self.sender = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    self.sender.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    self.sender.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
    self.sender.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 4)

    self.listener = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    self.listener.bind((self.listen, 1900))

    request = struct.pack('4sL', socket.inet_aton('239.255.255.250'), socket.INADDR_ANY)
    self.listener.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, request)
    self.listener.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 8192*2)
    # Make sure we don't get stuck longer than 1s so we also can notify
    self.listener.settimeout(1) 
Example 20
Project: ha-local-echo   Author: blocke   File: ha-local-echo.py    MIT License 5 votes vote down vote up
def run(self):

        # Listen for UDP port 1900 packets sent to SSDP multicast address
        print("UPNP Responder Thread started...")
        ssdpmc_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

        # Required for receiving multicast
        ssdpmc_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        ssdpmc_socket.setsockopt(socket.SOL_IP, socket.IP_MULTICAST_IF, socket.inet_aton(LISTEN_IP))
        ssdpmc_socket.setsockopt(socket.SOL_IP, socket.IP_ADD_MEMBERSHIP, socket.inet_aton("239.255.255.250") + socket.inet_aton(LISTEN_IP))

        ssdpmc_socket.bind(("239.255.255.250", 1900))

        while True:
            try:
                data, addr = ssdpmc_socket.recvfrom(1024)
            except socket.error as e:
                if stop_thread == True:
                    print("UPNP Reponder Thread closing socket and shutting down...")
                    ssdpmc_socket.close()
                    return
                print ("UPNP Responder socket.error exception occured: {0}".format(e.__str__))

            # SSDP M-SEARCH method received - respond to it unicast with our info
            if "M-SEARCH" in data.decode('utf-8'):
                print("UPNP Responder sending response to {0}:{1}".format(addr[0], addr[1]))
                ssdpout_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
                ssdpout_socket.sendto(self.UPNP_RESPONSE, addr)
                ssdpout_socket.close() 
Example 21
Project: SMA-EM   Author: datenschuft   File: sma-daemon.py    GNU General Public License v2.0 5 votes vote down vote up
def run(self):
		# prepare listen to socket-Multicast
		socketconnected = False
		while not socketconnected:
			#try:
			sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
			sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
			sock.bind(('', MCAST_PORT))
			try:
				mreq = struct.pack("4s4s", socket.inet_aton(MCAST_GRP), socket.inet_aton(ipbind))
				sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
				file = open(statusfile, "w")
				file.write('multicastgroup connected')
				file.close()
				socketconnected = True
			except BaseException:
				print('could not connect to mulicast group... rest a bit and retry')
				file = open(statusfile, "w")
				file.write('could not connect to mulicast group... rest a bit and retry')
				file.close()
				time.sleep(5)
		emparts = {}
		while True:
			#getting sma values
			try:
				emparts=smaem.readem(sock)
				for serial in serials:
					# process only known sma serials
					if serial==format(emparts['serial']):
						# running all enabled features
						for featurenr in featurelist:
							#print('>>> starting '+featurelist[featurenr]['name'])
							featurelist[featurenr]['feature'].run(emparts,featurelist[featurenr]['config'])
			except Exception as e:
				print("Daemon: Exception occured")
				print(e)
				pass
#Daemon - Coding 
Example 22
Project: open-recipe   Author: dspray95   File: udp.py    The Unlicense 5 votes vote down vote up
def _joinAddr2(self, interface, addr, join):
        addr = socket.inet_aton(addr)
        interface = socket.inet_aton(interface)
        if join:
            cmd = socket.IP_ADD_MEMBERSHIP
        else:
            cmd = socket.IP_DROP_MEMBERSHIP
        try:
            self.socket.setsockopt(socket.IPPROTO_IP, cmd, addr + interface)
        except socket.error as e:
            return failure.Failure(error.MulticastJoinError(addr, interface,
                                                            *e.args)) 
Example 23
Project: open-recipe   Author: dspray95   File: udp.py    The Unlicense 5 votes vote down vote up
def _joinAddr2(self, interface, addr, join):
        addr = socket.inet_aton(addr)
        interface = socket.inet_aton(interface)
        if join:
            cmd = socket.IP_ADD_MEMBERSHIP
        else:
            cmd = socket.IP_DROP_MEMBERSHIP
        try:
            self.socket.setsockopt(socket.IPPROTO_IP, cmd, addr + interface)
        except socket.error as e:
            return failure.Failure(error.MulticastJoinError(addr, interface, *e.args)) 
Example 24
Project: PyMoCap   Author: markkorput   File: optirx.py    MIT License 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 25
Project: mdcs-old   Author: CtrlC-Root   File: server.py    MIT License 5 votes vote down vote up
def run(self):
        # XXX disable looping multicast traffic back to this machine
        # self.socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 0)

        # XXX OS X needs SO_REUSEPORT set in addition to SO_REUSEADDR which is set as part of
        # SocketServer.BaseServer.server_bind() if allow_reuse_address is set
        # https://stackoverflow.com/a/14388707/937006
        if platform.system() == 'Darwin' and self.allow_reuse_address:
            self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)

        try:
            # bind and activate the server
            self.server_bind()
            self.server_activate()

        except:
            # close the server
            self.server_close()

            # propagate the error
            raise

        try:
            # join the multicast group
            self.socket.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, self._group_member)

            # process requests until stopped
            self.serve_forever()

        finally:
            # leave the multicast group
            self.socket.setsockopt(socket.IPPROTO_IP, socket.IP_DROP_MEMBERSHIP, self._group_member)

            # close the server
            self.server_close() 
Example 26
Project: pyaqara   Author: javefang   File: protocol.py    MIT License 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 27
Project: rpi3-webiopi   Author: thortex   File: coap.py    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 28
Project: Safejumper-for-Desktop   Author: proxysh   File: udp.py    GNU General Public License v2.0 5 votes vote down vote up
def _joinAddr2(self, interface, addr, join):
        addr = socket.inet_aton(addr)
        interface = socket.inet_aton(interface)
        if join:
            cmd = socket.IP_ADD_MEMBERSHIP
        else:
            cmd = socket.IP_DROP_MEMBERSHIP
        try:
            self.socket.setsockopt(socket.IPPROTO_IP, cmd, addr + interface)
        except socket.error as e:
            return failure.Failure(error.MulticastJoinError(addr, interface,
                                                            *e.args)) 
Example 29
Project: Safejumper-for-Desktop   Author: proxysh   File: udp.py    GNU General Public License v2.0 5 votes vote down vote up
def _joinAddr2(self, interface, addr, join):
        addr = socket.inet_aton(addr)
        interface = socket.inet_aton(interface)
        if join:
            cmd = socket.IP_ADD_MEMBERSHIP
        else:
            cmd = socket.IP_DROP_MEMBERSHIP
        try:
            self.socket.setsockopt(socket.IPPROTO_IP, cmd, addr + interface)
        except socket.error as e:
            return failure.Failure(error.MulticastJoinError(addr, interface, *e.args)) 
Example 30
Project: aioupnp   Author: lbryio   File: multicast.py    MIT License 5 votes vote down vote up
def join_group(self, multicast_address: str, bind_address: str) -> None:
        sock = self.sock
        if sock:
            sock.setsockopt(
                socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP,
                socket.inet_aton(multicast_address) + socket.inet_aton(bind_address)
            )
        return None 
Example 31
Project: switcheroo   Author: initstring   File: switcheroo.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, local_ip, local_port, target):
        self.sock = None
        self.known_hosts = []
        self.local_ip = local_ip
        self.local_port = local_port
        self.target = target
        ssdp_port = 1900  # Defined by SSDP spec, do not change
        mcast_group = '239.255.255.250'  # Defined by SSDP spec, do not change
        server_address = ('', ssdp_port)

        # The re below can help us identify obviously false requests
        # from detection tools.
        self.valid_st = re.compile(r'^[a-zA-Z0-9.\-_]+:[a-zA-Z0-9.\-_:]+$')

        # Generating a new unique USD/UUID may help prevent signature-like
        # detection tools.
        self.session_usn = ('uuid:'
                            + self.gen_random(8) + '-'
                            + self.gen_random(4) + '-'
                            + self.gen_random(4) + '-'
                            + self.gen_random(4) + '-'
                            + self.gen_random(12))

        # Create the socket
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        # Bind to the server address
        self.sock.bind(server_address)

        # Tell the operating system to add the socket to
        # the multicast group on for the interface on the specific IP.
        group = socket.inet_aton(mcast_group)
        mreq = struct.pack('4s4s', group, socket.inet_aton(self.local_ip))
        self.sock.setsockopt(
            socket.IPPROTO_IP,
            socket.IP_ADD_MEMBERSHIP,
            mreq) 
Example 32
Project: shtoom   Author: braams   File: unixspec.py    GNU Lesser General Public License v2.1 5 votes vote down vote up
def joinGroup(sock,addr):
    """Join a multicast group.
       arguments:
       sock = an already open socket.
       addr = either a string, which will be passed to gethostbyname(), or
       a 32 bit number (the string can be a DNS name, or a dotted quad.
"""
    mreq = _addr2mreq(addr)
    sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq) 
Example 33
Project: parlance   Author: cappachu   File: chat_controller.py    MIT License 5 votes vote down vote up
def setup_socket_recv(self):
        if self._sock_recv is None:
            # UDP socket
            self._sock_recv = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)#, socket.IPPROTO_UDP)
            # enable reuse
            self._sock_recv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            # 4sl: 4 chars followed by long 
            mreq = struct.pack("4sl", socket.inet_aton(MULTICAST_GROUP_IP), socket.INADDR_ANY)
            # add as member of multicast group
            self._sock_recv.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
        return self._sock_recv 
Example 34
Project: sacn   Author: Hundemeier   File: receiver.py    MIT License 5 votes vote down vote up
def join_multicast(self, universe: int) -> None:
        """
        Joins the multicast address that is used for the given universe. Note: If you are on Windows you must have given
        a bind IP-Address for this feature to function properly. On the other hand you are not allowed to set a bind
        address if you are on any other OS.
        :param universe: the universe to join the multicast group.
        The network hardware has to support the multicast feature!
        """
        self.sock.setsockopt(socket.SOL_IP, socket.IP_ADD_MEMBERSHIP,
                             socket.inet_aton(calculate_multicast_addr(universe)) +
                             socket.inet_aton(self._bindAddress)) 
Example 35
Project: uPyEcho   Author: lemariva   File: main.py    Apache License 2.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", inet_aton(self.ip), INADDR_ANY)
            # Set up server socket
            self.ssock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            self.ssock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            try:
                self.ssock.bind(("", self.port))
            except Exception as e:
                dbg("WARNING: Failed to bind %s:%d: %s", (self.ip, self.port, e))
                ok = False
            try:
                dbg(
                    "IP: "
                    + str(socket.IPPROTO_IP)
                    + " IP_ADD_MEMBERSHIP: "
                    + str(socket.IP_ADD_MEMBERSHIP)
                    + " mreq: "
                    + str(self.mreq)
                )
                self.ssock.setsockopt(
                    socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, self.mreq
                )
            except Exception as e:
                dbg("WARNING: Failed to join multicast group!: " + str(e))
                ok = False

        except Exception as e:
            dbg("Failed to initialize UPnP sockets!")
            return False
        if ok:
            dbg("Listening for UPnP broadcasts") 
Example 36
Project: weibo_twitter_earnings_analysis   Author: lynings   File: udp.py    Apache License 2.0 5 votes vote down vote up
def _joinAddr2(self, interface, addr, join):
        addr = socket.inet_aton(addr)
        interface = socket.inet_aton(interface)
        if join:
            cmd = socket.IP_ADD_MEMBERSHIP
        else:
            cmd = socket.IP_DROP_MEMBERSHIP
        try:
            self.socket.setsockopt(socket.IPPROTO_IP, cmd, addr + interface)
        except socket.error as e:
            return failure.Failure(error.MulticastJoinError(addr, interface,
                                                            *e.args)) 
Example 37
Project: weibo_twitter_earnings_analysis   Author: lynings   File: udp.py    Apache License 2.0 5 votes vote down vote up
def _joinAddr2(self, interface, addr, join):
        addr = socket.inet_aton(addr)
        interface = socket.inet_aton(interface)
        if join:
            cmd = socket.IP_ADD_MEMBERSHIP
        else:
            cmd = socket.IP_DROP_MEMBERSHIP
        try:
            self.socket.setsockopt(socket.IPPROTO_IP, cmd, addr + interface)
        except socket.error as e:
            return failure.Failure(error.MulticastJoinError(addr, interface, *e.args)) 
Example 38
Project: VideoServer   Author: shaolo1   File: video_server_aiohttp.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, server):
        self._server = server

        @asyncio.coroutine
        def _connect():
            info = socket.getaddrinfo(SSDPServer.ADDRESS, None)[0]
            sock = socket.socket(info[0], socket.SOCK_DGRAM)
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
            group_bin = socket.inet_pton(info[0], info[4][0])
            sock.bind(('', SSDPServer.PORT))
            if info[0] == socket.AF_INET:  # IPv4
                group = group_bin + struct.pack('=I', socket.INADDR_ANY)
                sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, group)
            else:
                group = group_bin + struct.pack('@I', 0)
                sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_JOIN_GROUP, group)
            yield from asyncio.get_event_loop().create_datagram_endpoint(lambda: self, sock=sock)

        def _run(loop):
            asyncio.set_event_loop(loop)
            loop.run_forever()
            loop.close()

        self.io_loop = asyncio.new_event_loop()
        asyncio.run_coroutine_threadsafe(_connect(), loop=self.io_loop)
        Thread(target=_run, args=(self.io_loop,)).start()

        self._devices_local = {}
        self._transport = None 
Example 39
Project: VideoServer   Author: shaolo1   File: video_server_quart.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, server):
        self._server = server

        @asyncio.coroutine
        def _connect():
            info = socket.getaddrinfo(SSDPServer.ADDRESS, None)[0]
            sock = socket.socket(info[0], socket.SOCK_DGRAM)
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
            group_bin = socket.inet_pton(info[0], info[4][0])
            sock.bind(('', SSDPServer.PORT))
            if info[0] == socket.AF_INET:  # IPv4
                group = group_bin + struct.pack('=I', socket.INADDR_ANY)
                sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, group)
            else:
                group = group_bin + struct.pack('@I', 0)
                sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_JOIN_GROUP, group)
            yield from asyncio.get_event_loop().create_datagram_endpoint(lambda: self, sock=sock)

        def _run(loop):
            asyncio.set_event_loop(loop)
            loop.run_forever()
            loop.close()

        self.io_loop = asyncio.new_event_loop()
        asyncio.run_coroutine_threadsafe(_connect(), loop=self.io_loop)
        Thread(target=_run, args=(self.io_loop,)).start()

        self._devices_local = {}
        self._transport = None 
Example 40
Project: VideoServer   Author: shaolo1   File: video_server.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, server):
        self._server = server

        @asyncio.coroutine
        def _connect():
            info = socket.getaddrinfo(SSDPServer.ADDRESS, None)[0]
            sock = socket.socket(info[0], socket.SOCK_DGRAM)
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
            group_bin = socket.inet_pton(info[0], info[4][0])
            sock.bind(('', SSDPServer.PORT))
            if info[0] == socket.AF_INET:  # IPv4
                group = group_bin + struct.pack('=I', socket.INADDR_ANY)
                sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, group)
            else:
                group = group_bin + struct.pack('@I', 0)
                sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_JOIN_GROUP, group)
            yield from asyncio.get_event_loop().create_datagram_endpoint(lambda: self, sock=sock)

        def _run(loop):
            asyncio.set_event_loop(loop)
            loop.run_forever()
            loop.close()

        self.io_loop = asyncio.new_event_loop()
        asyncio.run_coroutine_threadsafe(_connect(), loop=self.io_loop)
        Thread(target=_run, args=(self.io_loop,)).start()

        self._devices_local = {}
        self._transport = None 
Example 41
Project: learn_python3_spider   Author: wistbean   File: udp.py    MIT License 5 votes vote down vote up
def _joinAddr2(self, interface, addr, join):
        addr = socket.inet_aton(addr)
        interface = socket.inet_aton(interface)
        if join:
            cmd = socket.IP_ADD_MEMBERSHIP
        else:
            cmd = socket.IP_DROP_MEMBERSHIP
        try:
            self.socket.setsockopt(socket.IPPROTO_IP, cmd, addr + interface)
        except socket.error as e:
            return failure.Failure(error.MulticastJoinError(addr, interface,
                                                            *e.args)) 
Example 42
Project: learn_python3_spider   Author: wistbean   File: udp.py    MIT License 5 votes vote down vote up
def _joinAddr2(self, interface, addr, join):
        addr = socket.inet_aton(addr)
        interface = socket.inet_aton(interface)
        if join:
            cmd = socket.IP_ADD_MEMBERSHIP
        else:
            cmd = socket.IP_DROP_MEMBERSHIP
        try:
            self.socket.setsockopt(socket.IPPROTO_IP, cmd, addr + interface)
        except socket.error as e:
            return failure.Failure(error.MulticastJoinError(addr, interface, *e.args)) 
Example 43
Project: xknx   Author: XKNX   File: udp_client.py    MIT License 5 votes vote down vote up
def create_multicast_sock(own_ip, remote_addr, bind_to_multicast_addr):
        """Create UDP multicast socket."""
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.setblocking(False)

        sock.setsockopt(
            socket.SOL_IP,
            socket.IP_MULTICAST_IF,
            socket.inet_aton(own_ip))
        sock.setsockopt(
            socket.SOL_IP,
            socket.IP_ADD_MEMBERSHIP,
            socket.inet_aton(remote_addr[0]) +
            socket.inet_aton(own_ip))
        sock.setsockopt(
            socket.IPPROTO_IP,
            socket.IP_MULTICAST_TTL, 2)
        sock.setsockopt(
            socket.IPPROTO_IP,
            socket.IP_MULTICAST_IF,
            socket.inet_aton(own_ip))

        # I have no idea why we have to use different bind calls here
        # - bind() with multicast addr does not work with gateway search requests
        #   on some machines. It only works if called with own ip. It also doesn't
        #   work on Mac OS.
        # - bind() with own_ip does not work with ROUTING_INDICATIONS on Gira
        #   knx router - for an unknown reason.
        if bind_to_multicast_addr:
            sock.bind((remote_addr[0], remote_addr[1]))
        else:
            sock.bind((own_ip, 0))
        sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 0)
        return sock 
Example 44
Project: rext   Author: j91321   File: upnp_console.py    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 45
Project: hmv-s16   Author: cmuphyscomp   File: optirx.py    BSD 3-Clause "New" or "Revised" License 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 46
Project: Legion   Author: MooseDojo   File: multicast.py    MIT License 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 47
Project: share-gaze   Author: marcus-nystrom   File: CastThread.py    MIT License 5 votes vote down vote up
def __init__(self,  myIP="169.254.173.49", dcMultiPort=10000, dcMultiIP="224.0.0.9"):

        self.myIP = myIP
        # Ports that we send and receive on:
        self.dcMultiPort = dcMultiPort
        self.dcMultiIP = dcMultiIP
        self.multicastGroup = (dcMultiIP, dcMultiPort)

        # Create Socket object
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

        #TODO : Check meaning of this binding 'bind':
        self.server_address = ('', 10000)
        self.sock.bind(self.server_address)
        # TODO: internet suggests to use bind to the self.multicastGroup. difference is that if
        # ip is '', you get data from all multicast groups, if specific group ip, then you only get
        # data from that group

        # Tell the operating system to add the socket to the multicast group
        # on all interfaces.
        group = socket.inet_aton(dcMultiIP)
        self.mreq = struct.pack('4sL', group, socket.INADDR_ANY)
        self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, self.mreq)
        # by defualt, don't receive own data:
        self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 0)
        # blocking, but with non-infinite timeout
        self.sock.settimeout(1)
        #self.sock.setblocking(0)
        self.buffer = 1024
        
        # deque for client to read from
        self.outputBuffer = deque()
        #self.outputBuffer = None

        # UDP port to listen and send x,y from sim or eyetracker data on.

        # create self as a thread
        threading.Thread.__init__(self)

        self.__stop = False 
Example 48
Project: pyShelly   Author: StyraHem   File: coap.py    MIT License 5 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.host_ip, COAP_PORT))
        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 49
Project: pyShelly   Author: StyraHem   File: mdns.py    MIT License 5 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.host_ip, MDNS_PORT))
        mreq = struct.pack("=4sl", socket.inet_aton(MDNS_IP),
                           socket.INADDR_ANY)
        sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
        sock.settimeout(15)
        self._socket = sock 
Example 50
Project: llamar   Author: culler   File: responder.py    GNU General Public License v2.0 5 votes vote down vote up
def _create_UDP_socket(self, family, address):
        AF = socket.AF_INET if family=='inet' else socket.AF_INET6
        try:
            udpsocket = socket.socket(AF,
                                      socket.SOCK_DGRAM,
                                      socket.IPPROTO_UDP)
            udpsocket.setsockopt(socket.SOL_SOCKET,
                                 socket.SO_REUSEADDR,
                                 1)
            udpsocket.bind( ('', LLMNR_PORT) )
            group = LLMNR_addrs[AF]
            if family == 'inet':
                udpsocket.setsockopt(socket.SOL_IP,
                                     IP_PKTINFO,
                                     1)
                membership_request = struct.pack('!4sl',
                                                 socket.inet_aton(group),
                                                 socket.INADDR_ANY)
                udpsocket.setsockopt(socket.IPPROTO_IP,
                                     socket.IP_ADD_MEMBERSHIP,
                                     membership_request)
            else:
                udpsocket.setsockopt(socket.IPPROTO_IPV6,
                                     socket.IPV6_RECVPKTINFO,
                                     1)
                membership_request = struct.pack('!16sI',
                                                 socket.inet_pton(AF, group),
                                                 socket.INADDR_ANY)
                udpsocket.setsockopt(socket.IPPROTO_IPV6,
                                     socket.IPV6_JOIN_GROUP,
                                     membership_request)
            return udpsocket
        except socket.error as e:
            if udpsocket != None:
                udpsocket.close()
            logger.error('Error in _create_UDP_socket.', exc_info=True) 
Example 51
Project: plugandpray   Author: dev-zzo   File: plugandpray.py    MIT License 5 votes vote down vote up
def __init__(self, remote_addr, bind_addr, timeout=5):
        """Initialise the transport.
        
        remote_addr: remote endpoint address (as in socket address)
        bind_addr: local address to bind to (as in socket address)
        """
        HttpUdpTransport.__init__(self, remote_addr, timeout)
        self.s.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 32)
        mreq = socket.inet_aton(remote_addr[0]) + socket.inet_aton(bind_addr[0])
        self.s.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq) 
Example 52
Project: yamaha   Author: rthill   File: __init__.py    GNU General Public License v3.0 5 votes vote down vote up
def mcast_add(self, addr):
        self.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP,
                        socket.inet_aton(addr) + socket.inet_aton('0.0.0.0')) 
Example 53
Project: aqara-mqtt   Author: monster1025   File: xiaomihub.py    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 54
Project: pydak   Author: fimion   File: __init__.py    MIT License 5 votes vote down vote up
def __init__(self, data=21000):
        self.data = None
        self.data = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        self.data.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.data.bind(('', data))
        mreq = struct.pack("=4sl", socket.inet_aton(DAKUDP_IP), socket.INADDR_ANY)
        self.data.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq) 
Example 55
Project: panonoctl   Author: florianl   File: ssdp.py    Apache License 2.0 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 56
Project: server   Author: lowitty   File: udp.py    MIT License 5 votes vote down vote up
def _joinAddr2(self, interface, addr, join):
        addr = socket.inet_aton(addr)
        interface = socket.inet_aton(interface)
        if join:
            cmd = socket.IP_ADD_MEMBERSHIP
        else:
            cmd = socket.IP_DROP_MEMBERSHIP
        try:
            self.socket.setsockopt(socket.IPPROTO_IP, cmd, addr + interface)
        except socket.error, e:
            return failure.Failure(error.MulticastJoinError(addr, interface,
                                                            *e.args)) 
Example 57
Project: server   Author: lowitty   File: udp.py    MIT License 5 votes vote down vote up
def _joinAddr2(self, interface, addr, join):
        addr = socket.inet_aton(addr)
        interface = socket.inet_aton(interface)
        if join:
            cmd = socket.IP_ADD_MEMBERSHIP
        else:
            cmd = socket.IP_DROP_MEMBERSHIP
        try:
            self.socket.setsockopt(socket.IPPROTO_IP, cmd, addr + interface)
        except socket.error as e:
            return failure.Failure(error.MulticastJoinError(addr, interface, *e.args)) 
Example 58
Project: server   Author: lowitty   File: udp.py    MIT License 5 votes vote down vote up
def _joinAddr2(self, interface, addr, join):
        addr = socket.inet_aton(addr)
        interface = socket.inet_aton(interface)
        if join:
            cmd = socket.IP_ADD_MEMBERSHIP
        else:
            cmd = socket.IP_DROP_MEMBERSHIP
        try:
            self.socket.setsockopt(socket.IPPROTO_IP, cmd, addr + interface)
        except socket.error, e:
            return failure.Failure(error.MulticastJoinError(addr, interface,
                                                            *e.args)) 
Example 59
Project: server   Author: lowitty   File: udp.py    MIT License 5 votes vote down vote up
def _joinAddr2(self, interface, addr, join):
        addr = socket.inet_aton(addr)
        interface = socket.inet_aton(interface)
        if join:
            cmd = socket.IP_ADD_MEMBERSHIP
        else:
            cmd = socket.IP_DROP_MEMBERSHIP
        try:
            self.socket.setsockopt(socket.IPPROTO_IP, cmd, addr + interface)
        except socket.error as e:
            return failure.Failure(error.MulticastJoinError(addr, interface, *e.args)) 
Example 60
Project: BnB   Author: bizzo6   File: gateway_listener.py    GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, port=MCAST_PORT, buffsize=BUFFER_SIZE, addr=MCAST_ADDRESS):
        self.logger = logging.getLogger(libs.bnbutils.LOGGING_LOGGER_NAME)
        self.ipc = libs.bnbipc.bnbipc()
        self.port = port
        self.addr = addr
        self.bufferSize = buffsize

        # Init Socket for listening

        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(('', self.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(self.addr), socket.INADDR_ANY)
        self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq) 
Example 61
Project: script.tubecast   Author: enen92   File: ssdp.py    MIT License 5 votes vote down vote up
def __init__(self, addr, handler, poll_interval=0.5, bind_and_activate=True, interfaces=None):
        ThreadingUDPServer.__init__(self, ('', addr[1]),
                                    handler,
                                    bind_and_activate)
        ControlMixin.__init__(self, handler, poll_interval)
        self._multicast_address = addr
        self._listen_interfaces = interfaces
        self.set_loopback_mode(1)  # localhost
        self.set_ttl(2)  # localhost and local network
        self.handle_membership(socket.IP_ADD_MEMBERSHIP) 
Example 62
Project: tv_grab_es_movistartv   Author: MovistarTV   File: tv_grab_es_movistartv.py    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 63
Project: py-wsjtx   Author: bmo   File: simple_server.py    MIT License 5 votes vote down vote up
def multicast_setup(self, group, port=''):
        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(('', port))
        mreq = struct.pack("4sl", socket.inet_aton(group), socket.INADDR_ANY)
        self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq) 
Example 64
Project: HRTunerProxy   Author: OpenViX   File: ssdp.py    GNU General Public License v2.0 5 votes vote down vote up
def run(self):
		self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
		self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
		if hasattr(socket, "SO_REUSEPORT"):
			try:
				self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
			except socket.error as le:
				# RHEL6 defines SO_REUSEPORT but it doesn't work
				if le.errno == ENOPROTOOPT:
					pass
				else:
					raise

		addr = socket.inet_aton(SSDP_ADDR)
		interface = socket.inet_aton('0.0.0.0')
		cmd = socket.IP_ADD_MEMBERSHIP
		self.sock.setsockopt(socket.IPPROTO_IP, cmd, addr + interface)
		self.sock.bind(('0.0.0.0', SSDP_PORT))
		self.sock.settimeout(1)

		while True:
			try:
				data, addr = self.sock.recvfrom(1024)
				self.datagram_received(data, addr)
			except socket.timeout:
				continue
		self.shutdown() 
Example 65
Project: python_natnet   Author: mje-nz   File: comms.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def bind_data_socket(self, multicast_addr, data_port):
        """Bind data socket and begin receiving mocap frames.

        Args:
            multicast_addr (str): Server's IPv4 multicast address
            data_port (int): Server's data port
        """
        # Join multicast group
        mreq = struct.pack("4sl", socket.inet_aton(multicast_addr), socket.INADDR_ANY)
        self._data_socket.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
        # Bind to data port
        self._data_socket.bind(('', data_port)) 
Example 66
Project: neutron-tempest-plugin   Author: openstack   File: test_multicast.py    Apache License 2.0 5 votes vote down vote up
def get_receiver_script(group, port, hello_message, ack_message, result_file):

    return """
import socket
import struct
import sys

multicast_group = '%(group)s'
server_address = ('', %(port)s)

# Create the socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)

# Bind to the server address
sock.bind(server_address)

# 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)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)

# Receive/respond loop
with open('%(result_file)s', 'w') as f:
    f.write('%(hello_message)s')
    f.flush()
    data, address = sock.recvfrom(1024)
    f.write('received ' + str(len(data)) + ' bytes from ' + str(address))
    f.write(str(data))
sock.sendto(b'%(ack_message)s', address)
    """ % {'group': group,
           'port': port,
           'hello_message': hello_message,
           'ack_message': ack_message,
           'result_file': result_file} 
Example 67
Project: python-for-android   Author: kuri65536   File: udp.py    Apache License 2.0 5 votes vote down vote up
def _joinAddr2(self, interface, addr, join):
        addr = socket.inet_aton(addr)
        interface = socket.inet_aton(interface)
        if join:
            cmd = socket.IP_ADD_MEMBERSHIP
        else:
            cmd = socket.IP_DROP_MEMBERSHIP
        try:
            self.socket.setsockopt(socket.IPPROTO_IP, cmd, addr + interface)
        except socket.error, e:
            return failure.Failure(error.MulticastJoinError(addr, interface,
                                                            *e.args)) 
Example 68
Project: python-for-android   Author: kuri65536   File: udp.py    Apache License 2.0 5 votes vote down vote up
def _joinAddr2(self, interface, addr, join):
        addr = socket.inet_aton(addr)
        interface = socket.inet_aton(interface)
        if join:
            cmd = socket.IP_ADD_MEMBERSHIP
        else:
            cmd = socket.IP_DROP_MEMBERSHIP
        try:
            self.socket.setsockopt(socket.IPPROTO_IP, cmd, addr + interface)
        except socket.error, e:
            return failure.Failure(error.MulticastJoinError(addr, interface, *e.args)) 
Example 69
Project: HomeAssistant_Components   Author: charleyzhu   File: upnp.py    Apache License 2.0 4 votes vote down vote up
def run(self):
        """Run the server."""
        # Listen for UDP port 1900 packets sent to SSDP multicast address
        ssdp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        ssdp_socket.setblocking(False)

        # Required for receiving multicast
        ssdp_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        ssdp_socket.setsockopt(
            socket.SOL_IP,
            socket.IP_MULTICAST_IF,
            socket.inet_aton(self.host_ip_addr))

        ssdp_socket.setsockopt(
            socket.SOL_IP,
            socket.IP_ADD_MEMBERSHIP,
            socket.inet_aton("239.255.255.250") +
            socket.inet_aton(self.host_ip_addr))

        if self.upnp_bind_multicast:
            ssdp_socket.bind(("", 1900))
        else:
            ssdp_socket.bind((self.host_ip_addr, 1900))

        while True:
            if self._interrupted:
                clean_socket_close(ssdp_socket)
                return

            try:
                read, _, _ = select.select(
                    [ssdp_socket], [],
                    [ssdp_socket], 2)

                if ssdp_socket in read:
                    data, addr = ssdp_socket.recvfrom(1024)
                else:
                    # most likely the timeout, so check for interrupt
                    continue
            except socket.error as ex:
                if self._interrupted:
                    clean_socket_close(ssdp_socket)
                    return

                _LOGGER.error("UPNP Responder socket exception occurred: %s",
                              ex.__str__)
                # without the following continue, a second exception occurs
                # because the data object has not been initialized
                continue

            if "M-SEARCH" in data.decode('utf-8', errors='ignore'):
                # SSDP M-SEARCH method received, respond to it with our info
                resp_socket = socket.socket(
                    socket.AF_INET, socket.SOCK_DGRAM)

                resp_socket.sendto(self.upnp_response, addr)
                resp_socket.close() 
Example 70
Project: diamond-next   Author: diamond-next   File: collectd_network.py    MIT License 4 votes vote down vote up
def __init__(self, host=None, port=DEFAULT_PORT, multicast=False):
        if host is None:
            multicast = True
            host = DEFAULT_IPv4_GROUP

        self.host, self.port = host, port
        self.ipv6 = ":" in self.host

        if multicast:
            hostname = None
        else:
            hostname = self.host

        if self.ipv6:
            sock_type = socket.AF_INET6
        else:
            sock_type = socket.AF_UNSPEC

        family, socktype, proto, canonname, sockaddr = socket.getaddrinfo(
            hostname,
            self.port,
            sock_type,
            socket.SOCK_DGRAM, 0, socket.AI_PASSIVE)[0]

        self._sock = socket.socket(family, socktype, proto)
        self._sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self._sock.bind(sockaddr)

        if multicast:
            if hasattr(socket, "SO_REUSEPORT"):
                self._sock.setsockopt(
                    socket.SOL_SOCKET,
                    socket.SO_REUSEPORT, 1)

            val = None
            if family == socket.AF_INET:
                assert "." in self.host
                val = struct.pack("4sl",
                                  socket.inet_aton(self.host),
                                  socket.INADDR_ANY)
            elif family == socket.AF_INET6:
                raise NotImplementedError("IPv6 support not ready yet")
            else:
                raise ValueError("Unsupported network address family")

            if self.ipv6:
                sock_type = socket.IPPROTO_IPV6
            else:
                sock_type = socket.IPPROTO_IP

            self._sock.setsockopt(
                sock_type,
                socket.IP_ADD_MEMBERSHIP, val)
            self._sock.setsockopt(
                sock_type,
                socket.IP_MULTICAST_LOOP, 0)

        self._readlist = [self._sock] 
Example 71
Project: mdns-lookup   Author: AndreMiras   File: mdnslookup.py    MIT License 4 votes vote down vote up
def lookup(hosts):
    """
    Returns a host/ip dictionary for the given host list.
    """
    hosts_ip = dict.fromkeys(hosts)
    UDP_IP = "0.0.0.0"
    UDP_PORT = 5353
    MCAST_GRP = '224.0.0.251'
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.bind((UDP_IP, UDP_PORT))
    # join the multicast group
    mreq = struct.pack("4sl", socket.inet_aton(MCAST_GRP), socket.INADDR_ANY)
    sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)

    for host in hosts:
        # the string in the following statement is an empty query packet
        dns = DNS(
                '\x00\x00\x01\x00\x00\x01\x00\x00' +
                '\x00\x00\x00\x00\x00\x00\x01\x00\x01')
        dns.qd[0].name = host
        sock.sendto(dns.pack(), (MCAST_GRP, UDP_PORT))
    # receives until the end of the timeout
    sock.settimeout(5)
    while True:
        try:
            m = sock.recvfrom(1024)
            if VERBOSE_GLOBAL:
                print('%r %s' % (m[0], m[1]))
            dns = DNS(m[0])
            if len(dns.qd) > 0:
                if VERBOSE_GLOBAL:
                    print("%r %s" % (dns, dns.qd[0].name))
            if len(dns.an) > 0 and dns.an[0].type == DNS_A:
                host = dns.an[0].name
                ip = socket.inet_ntoa(dns.an[0].rdata)
                if VERBOSE_GLOBAL:
                    print("%r %s %s" % (dns, host, ip))
                hosts_ip[host] = ip
        except socket.timeout:
            break
    return hosts_ip 
Example 72
Project: share-gaze   Author: marcus-nystrom   File: CastThread.py    MIT License 4 votes vote down vote up
def __init__(self,  myIP="169.254.173.49", dcMultiPort=10000, dcMultiIP="224.0.0.9"):

        self.myIP = myIP
        # Ports that we send and receive on:
        self.dcMultiPort = dcMultiPort
        self.dcMultiIP = dcMultiIP
        self.multicastGroup = (dcMultiIP, dcMultiPort)

        # Create Socket object
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        
        # do not request exclusive access to the socket (or something loike that), should sovle the issue where a socket appears blocked
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        #TODO : Check meaning of this binding 'bind':
        self.server_address = ('', dcMultiPort)
        self.sock.bind(self.server_address)
        # TODO: internet suggests to use bind to the self.multicastGroup. difference is that if
        # ip is '', you get data from all multicast groups, if specific group ip, then you only get
        # data from that group

        # Tell the operating system to add the socket to the multicast group
        # on all interfaces.
        group = socket.inet_aton(dcMultiIP)
        self.mreq = struct.pack('4sL', group, socket.INADDR_ANY)
        self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, self.mreq)
        # by defualt, don't receive own data:
        self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 0)
        # blocking, but with non-infinite timeout
        self.sock.settimeout(1)
        #self.sock.setblocking(0)
        self.buffer = 1024
        
        # deque for client to read from
        self.outputBuffer = deque()
        #self.outputBuffer = None
        self.outputCache  = [None for i in range(32)]   # each computer will have one slot in here, by IP address. Our's go till 28, have a few extra in case assigned by DHCP

        # UDP port to listen and send x,y from sim or eyetracker data on.

        # create self as a thread
        threading.Thread.__init__(self)

        self.__stop = False 
Example 73
Project: VirtuCameraMaya   Author: shycats   File: zeroconf.py    MIT License 4 votes vote down vote up
def __init__(self, bindaddress=None):
        """Creates an instance of the Zeroconf class, establishing
        multicast communications, listening and reaping threads."""
        global _GLOBAL_DONE
        _GLOBAL_DONE = False
        if bindaddress is None:
            try:
                s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
                s.connect(('4.2.2.1', 123))
                self.intf = s.getsockname()[0]
            except Exception as e:  # TODO stop catching all Exceptions
                log.exception('Unknown error, possibly benign: %r', e)
                self.intf = socket.gethostbyname(socket.gethostname())
        else:
            self.intf = bindaddress
        log.debug('Bind address is %r' % (self.intf,))
        self.group = (self.intf, _MDNS_PORT)
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        try:
            self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
        except Exception as e:  # TODO stop catching all Exceptions
            # SO_REUSEADDR should be equivalent to SO_REUSEPORT for
            # multicast UDP sockets (p 731, "TCP/IP Illustrated,
            # Volume 2"), but some BSD-derived systems require
            # SO_REUSEPORT to be specified explicity.  Also, not all
            # versions of Python have SO_REUSEPORT available.
            #
            log.exception('Unknown error, possibly benign: %r', e)

        self.socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 255)
        self.socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 1)
        try:
            log.debug('Binding to %r', self.group)
            self.socket.bind(self.group)
        except Exception as e:  # TODO stop catching all Exceptions
            # Some versions of linux raise an exception even though
            # the SO_REUSE* options have been set, so ignore it
            #
            log.exception('Unknown error, possibly benign: %r', e)
        # self.socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_IF,
        #    socket.inet_aton(self.intf) + socket.inet_aton('0.0.0.0'))
        self.socket.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP,
                               socket.inet_aton(_MDNS_ADDR) + socket.inet_aton('0.0.0.0'))

        self.listeners = []
        self.browsers = []
        self.services = {}
        self.servicetypes = {}

        self.cache = DNSCache()

        self.condition = threading.Condition()

        self.engine = Engine(self)
        self.listener = Listener(self)
        self.reaper = Reaper(self) 
Example 74
Project: upnp-hacks   Author: armijnhemel   File: upnpssdp.py    MIT License 4 votes vote down vote up
def run(self):
        # create two sockets, add them to the broadcast group and
        # make sure that the address can be reused (Linux only, for BSD
        # you should use other options).
        self.sendingsocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        self.receivingsocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        self.sendingsocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.sendingsocket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
        self.receivingsocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.receivingsocket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)

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

        mreq = struct.pack("4sl", socket.inet_aton("239.255.255.250"), socket.INADDR_ANY)
        self.receivingsocket.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)

        logfile = open(self.logfile, 'w+')
        logfile.write("logfile open\n")
        logfile.flush()

        self.sendingsocket.bind(('', 1900))
        self.receivingsocket.bind(('', 1900))
        self.sendingsocket.connect((host, 1900))
        print "Sending discovery message on: %s, port %s " % self.sendingsocket.getpeername()
        print "Listening on: %s, port %s\n" % self.sendingsocket.getsockname()
        self.msg = ""
        self.msg = self.msg + "M-SEARCH * HTTP/1.1\r\n"
        self.msg = self.msg + "HOST: 239.255.255.250:1900\r\n"
        self.msg = self.msg + "MAN: ssdp:discover\r\n"
        self.msg = self.msg + "MX: 10\r\n"
        self.msg = self.msg + "ST: ssdp:all\r\n"
        self.msg = self.msg + "\r\n"
        self.msg = self.msg + "\r\n"
        logfile.write("sending msg\n")
        logfile.write(self.msg)
        self.sendingsocket.send(self.msg)
        logfile.write("message sent\n")
        logfile.flush()

        print "Listening...\n"
        sys.stdout.flush()

        while (1):
            print "Waiting for SSDP data at", datetime.datetime.utcnow().isoformat()
            sys.stdout.flush()
            (data, client) = self.receivingsocket.recvfrom(1024)
            logfile.write(data)
            tempres = self.parsedata(data, client[0])
            self.filter_hosts(tempres)
            logfile.write(client[0])
            logfile.write("\n")
            logfile.flush()
            print
            sys.stdout.flush() 
Example 75
Project: pyShelly   Author: StyraHem   File: mdns.py    MIT License 4 votes vote down vote up
def _loop(self):

        #time.sleep(10)  #Just wait some sec to get names from cloud etc

        next_igmp_fix = datetime.now() + timedelta(minutes=1)

        while not self._root.stopped.isSet():

            try:

                # This fix is needed if not sending IGMP reports correct
                if self._root.igmp_fix_enabled and \
                        datetime.now() > next_igmp_fix:
                    LOGGER.debug("IGMP fix")
                    next_igmp_fix = datetime.now() + timedelta(minutes=1)
                    mreq = struct.pack("=4sl", socket.inet_aton(MDNS_IP),
                                       socket.INADDR_ANY)
                    try:
                        self._socket.setsockopt(socket.IPPROTO_IP,
                                                socket.IP_DROP_MEMBERSHIP,
                                                mreq)
                    except Exception as e:
                        LOGGER.debug("Can't drop membership, %s", e)
                    try:
                        self._socket.setsockopt(socket.IPPROTO_IP,
                                                socket.IP_ADD_MEMBERSHIP, mreq)
                    except Exception as e:
                        LOGGER.debug("Can't add membership, %s", e)

                try:
                    data_tmp, addr = self._socket.recvfrom(1024)
                except socket.timeout:
                    continue

                ipaddr = addr[0]

                data = bytearray(data_tmp)

                # id = data[0]
                # flags = data[1]
                #question = data[2]
                answer = data[3]
                #authority = data[4]
                #additional = data[5]

                if (answer > 0):
                    LOGGER.debug("mDns msg: %s %s", ipaddr, data_tmp)
                    p = re.compile(b'shelly(?P<type>[a-z0-9-]+)-(?P<id>[A-F0-9]{6})\x05')
                    m = p.search(data_tmp)
                    if m:
                        LOGGER.debug("mDns match Shelly")
                        #, m.group('id')
                        self._root.add_device_by_ip(ipaddr, "mDns")

            except Exception as ex:
                exception_log(ex, "Error receiving mDns UDP") 
Example 76
Project: Neteria   Author: ShadowBlip   File: core.py    GNU General Public License v2.0 4 votes vote down vote up
def __init__(self, app, threading=True, stats=False, listen_address='',
                 listen_port=40080, listen_type="unicast", bufsize=10240):

        self.app = app
        self.threading = threading
        self.scheduler_thread = None
        self.listen_thread = None
        self.listen_address = listen_address
        self.listen_port = listen_port
        self.listen_type = listen_type
        self.bufsize = bufsize
        self.listening = False

        self.stats_enabled = stats
        self.stats = {}
        self.stats['bytes_sent'] = 0
        self.stats['bytes_recieved'] = 0
        self.stats['mbps_sent'] = 0.0
        self.stats['mbps_recieved'] = 0.0
        self.stats['last_bytes_sent'] = 0
        self.stats['last_bytes_recieved'] = 0
        self.stats['check_interval'] = 2.0

        # Set up our socket and bind to our listen address and port.
        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((listen_address, listen_port))

        # If this is a multicast receiver, set it up as such.
        if listen_type == "multicast":
            mreq = struct.pack(
                "4sl", socket.inet_aton(listen_address), socket.INADDR_ANY)
            self.sock.setsockopt(
                socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)

        # Create a list of callbacks that we can schedule to run while we're
        # listening.
        self.scheduled_calls = []

        # If stats are enabled, start a recurring task that will calculate our
        # network stats every x seconds.
        if stats:
            self.call_later(self.stats['check_interval'],
                            self.calculate_stats, None) 
Example 77
Project: kastodi   Author: kharts   File: zeroconf.py    GNU General Public License v2.0 4 votes vote down vote up
def __init__(
        self,
        interfaces=InterfaceChoice.All,
    ):
        """Creates an instance of the Zeroconf class, establishing
        multicast communications, listening and reaping threads.

        :type interfaces: :class:`InterfaceChoice` or sequence of ip addresses
        """
        global _GLOBAL_DONE
        _GLOBAL_DONE = False

        self._listen_socket = new_socket()
        interfaces = normalize_interface_choice(interfaces, socket.AF_INET)

        self._respond_sockets = []

        for i in interfaces:
            log.debug('Adding %r to multicast group', i)
            try:
                self._listen_socket.setsockopt(
                    socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP,
                    socket.inet_aton(_MDNS_ADDR) + socket.inet_aton(i))
            except socket.error as e:
                if get_errno(e) == errno.EADDRINUSE:
                    log.info(
                        'Address in use when adding %s to multicast group, '
                        'it is expected to happen on some systems', i,
                    )
                elif get_errno(e) == errno.EADDRNOTAVAIL:
                    log.info(
                        'Address not available when adding %s to multicast group, '
                        'it is expected to happen on some systems', i,
                    )
                    continue
                else:
                    raise

            respond_socket = new_socket()
            respond_socket.setsockopt(
                socket.IPPROTO_IP, socket.IP_MULTICAST_IF, socket.inet_aton(i))

            self._respond_sockets.append(respond_socket)

        self.listeners = []
        self.browsers = []
        self.services = {}
        self.servicetypes = {}

        self.cache = DNSCache()

        self.condition = threading.Condition()

        self.engine = Engine(self)
        self.listener = Listener(self)
        self.engine.add_reader(self.listener, self._listen_socket)
        self.reaper = Reaper(self) 
Example 78
Project: alexa-hue-bridge   Author: IndigoDomotics   File: discovery.py    The Unlicense 4 votes vote down vote up
def run(self):
        try:
            PLUGIN.responderLogger.debug("Responder.run called")
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
            self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
            try:
                self.sock.bind(('', UPNP_PORT))
                self.sock.setsockopt(socket.IPPROTO_IP,
                                socket.IP_ADD_MEMBERSHIP,
                                socket.inet_aton(BCAST_IP) + socket.inet_aton(PLUGIN.globals['alexaHueBridge'][self.ahbDevId]['host']))
                self.sock.settimeout(1)
                self.start_time = time.time()
                self.end_time = self.start_time + (PLUGIN.globals['alexaHueBridge'][self.ahbDevId]['discoveryExpiration'] * 60)
                while True:
                    try:
                        self.data, self.addr = self.sock.recvfrom(1024)

                        # Following code discards non-Echo network traffic if option set in plugin config
                        if PLUGIN.globals['amazonEchoDeviceFilterActive']:
                            if self.addr[0] not in PLUGIN.globals['amazonEchoDevices']:
                                if PLUGIN.globals['debug']['filter']:
                                    PLUGIN.responderLogger.debug("Responder.respond called from SKIPPED address '{}'".format(str(self.addr[0])))
                                continue

                        # Following code will only time out the Broadcaster Thread if PLUGIN.globals['alexaHueBridge'][self.ahbDevId]['discoveryExpiration'] > 0 (valid values 0 thru 10 inclusive)
                        # A value of zero means 'always on'
                        if PLUGIN.globals['alexaHueBridge'][self.ahbDevId]['discoveryExpiration'] and time.time() > self.end_time:
                            PLUGIN.responderLogger.debug("Responder.run thread timed out")
                            self.stop()
                            raise socket.error
                    except socket.error:
                        if self.interrupted:
                            PLUGIN.responderLogger.debug("Responder.run: self.interrupted: True")
                            PLUGIN.setDeviceDiscoveryState(False, self.ahbDevId)
                            self.sock.close()
                            return
                    else:
                        if M_SEARCH_REQ_MATCH in self.data:
                            PLUGIN.responderLogger.debug("Responder.run: received from {}: {}".format(self.addr, str(self.data)))
                            self.respond(self.addr)
            except socket.error as e:
                # This is the exception thrown when someone else has bound to the UPNP port, so write some errors and
                # stop the thread (which really isn't needed, but it logs a nice stop debug message).
                if e.errno == errno.EADDRINUSE:
                    
                    PLUGIN.responderLogger.error(u"'{}' Responder startup failed because another app or plugin is using the UPNP port.".format(indigo.devices[self.ahbDevId].name))
                    PLUGIN.responderLogger.error(u"Open a terminal window and type 'sudo lsof -i :{}' to see a list of processes that have bound to that port and quit those applications.".format(UPNP_PORT))
                    self.stop()
                elif e.errno == errno.EADDRNOTAVAIL:
                    PLUGIN.responderLogger.error(u"'{}' Responder startup failed because host address is not available.".format(indigo.devices[self.ahbDevId].name))
                    PLUGIN.responderLogger.error(u"Double check that the host is specified correctly in the Plugin Config. Correct if invalid and then reload the plugin.")
                    self.stop()
                else:
                    PLUGIN.responderLogger.error("'{}' Responder.run: socket error: {}".format(indigo.devices[self.ahbDevId].name, e))

            PLUGIN.setDeviceDiscoveryState(False, self.ahbDevId)
        except StandardError, e:
            PLUGIN.responderLogger.error(u"StandardError detected in Responder.Run for '{}'. Line '{}' has error='{}'".format(indigo.devices[self.ahbDevId].name, sys.exc_traceback.tb_lineno, e)) 
Example 79
Project: python-signalk-client   Author: ph1l   File: zeroconf.py    GNU General Public License v3.0 4 votes vote down vote up
def __init__(
        self,
        interfaces=InterfaceChoice.All,
    ):
        """Creates an instance of the Zeroconf class, establishing
        multicast communications, listening and reaping threads.

        :type interfaces: :class:`InterfaceChoice` or sequence of ip addresses
        """
        # hook for threads
        self._GLOBAL_DONE = False

        self._listen_socket = new_socket()
        interfaces = normalize_interface_choice(interfaces, socket.AF_INET)

        self._respond_sockets = []

        for i in interfaces:
            log.debug('Adding %r to multicast group', i)
            try:
                self._listen_socket.setsockopt(
                    socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP,
                    socket.inet_aton(_MDNS_ADDR) + socket.inet_aton(i))
            except socket.error as e:
                if get_errno(e) == errno.EADDRINUSE:
                    log.info(
                        'Address in use when adding %s to multicast group, '
                        'it is expected to happen on some systems', i,
                    )
                elif get_errno(e) == errno.EADDRNOTAVAIL:
                    log.info(
                        'Address not available when adding %s to multicast '
                        'group, it is expected to happen on some systems', i,
                    )
                    continue
                else:
                    raise

            respond_socket = new_socket()
            respond_socket.setsockopt(
                socket.IPPROTO_IP, socket.IP_MULTICAST_IF, socket.inet_aton(i))

            self._respond_sockets.append(respond_socket)

        self.listeners = []
        self.browsers = {}
        self.services = {}
        self.servicetypes = {}

        self.cache = DNSCache()

        self.condition = threading.Condition()

        self.engine = Engine(self)
        self.listener = Listener(self)
        self.engine.add_reader(self.listener, self._listen_socket)
        self.reaper = Reaper(self)

        self.debug = None 
Example 80
Project: my_hass_config   Author: ivencooli   File: zeroconf.py    MIT License 4 votes vote down vote up
def __init__(
        self,
        interfaces=InterfaceChoice.All,
    ):
        """Creates an instance of the Zeroconf class, establishing
        multicast communications, listening and reaping threads.

        :type interfaces: :class:`InterfaceChoice` or sequence of ip addresses
        """
        # hook for threads
        self._GLOBAL_DONE = False

        self._listen_socket = new_socket()
        interfaces = normalize_interface_choice(interfaces, socket.AF_INET)

        self._respond_sockets = []

        for i in interfaces:
            log.debug('Adding %r to multicast group', i)
            try:
                self._listen_socket.setsockopt(
                    socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP,
                    socket.inet_aton(_MDNS_ADDR) + socket.inet_aton(i))
            except socket.error as e:
                if get_errno(e) == errno.EADDRINUSE:
                    log.info(
                        'Address in use when adding %s to multicast group, '
                        'it is expected to happen on some systems', i,
                    )
                elif get_errno(e) == errno.EADDRNOTAVAIL:
                    log.info(
                        'Address not available when adding %s to multicast '
                        'group, it is expected to happen on some systems', i,
                    )
                    continue
                else:
                    raise

            respond_socket = new_socket()
            respond_socket.setsockopt(
                socket.IPPROTO_IP, socket.IP_MULTICAST_IF, socket.inet_aton(i))

            self._respond_sockets.append(respond_socket)

        self.listeners = []
        self.browsers = {}
        self.services = {}
        self.servicetypes = {}

        self.cache = DNSCache()

        self.condition = threading.Condition()

        self.engine = Engine(self)
        self.listener = Listener(self)
        self.engine.add_reader(self.listener, self._listen_socket)
        self.reaper = Reaper(self)

        self.debug = None