Python socket.IP_MULTICAST_TTL Examples

The following are 30 code examples of socket.IP_MULTICAST_TTL(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module socket , or try the search function .
Example #1
Source File: mcast.py    From android_universal with MIT License 6 votes vote down vote up
def sender(group):
    addrinfo = socket.getaddrinfo(group, None)[0]

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

    # Set Time-to-live (optional)
    ttl_bin = struct.pack('@i', MYTTL)
    if addrinfo[0] == socket.AF_INET: # IPv4
        s.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl_bin)
    else:
        s.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_HOPS, ttl_bin)

    while True:
        data = repr(time.time()).encode('utf-8') + b'\0'
        s.sendto(data, (addrinfo[4][0], MYPORT))
        time.sleep(1) 
Example #2
Source File: listener.py    From pulseaudio-dlna with GNU General Public License v3.0 6 votes vote down vote up
def run(self, ttl=None):
        if self.DISABLE_SSDP_LISTENER:
            return

        self.allow_reuse_address = True
        SocketServer.UDPServer.__init__(
            self, (self.host or '', self.SSDP_PORT), SSDPHandler)
        self.socket.setsockopt(
            socket.IPPROTO_IP,
            socket.IP_ADD_MEMBERSHIP,
            self._multicast_struct(self.SSDP_ADDRESS))
        self.socket.setsockopt(
            socket.IPPROTO_IP,
            socket.IP_MULTICAST_TTL,
            self.SSDP_TTL)

        if ttl:
            GObject.timeout_add(ttl * 1000, self.shutdown)

        setproctitle.setproctitle('ssdp_listener')
        self.serve_forever(self)
        logger.info('SSDPListener.run()') 
Example #3
Source File: rokuAddr.py    From sensorReporter with Apache License 2.0 6 votes vote down vote up
def checkState(self):
        """Detects and publishes any state change"""
        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.sendto(self.ssdpRequest, ("239.255.255.250", 1900))
        while True:
            try:
                resp = sock.recv(1024)
                matchObj = re.match(r'.*USN: uuid:roku:ecp:([\w\d]{12}).*LOCATION: (http://.*/).*', resp, re.S)
                name = matchObj.group(1)
                ip = matchObj.group(2)
                if name not in sorted(self.ips.keys()) or self.ips[name] != ip:
                  self.logger.info('%s is now at %s' % (name, ip))
                  self.ips[name] = ip
                  self.publish(self.ips[name], self.rokus[name])
                else :
                  self.logger.info('%s is still at %s' % (name, ip))
            except socket.timeout:
                break
        sock.close() 
Example #4
Source File: mcast.py    From odoo13-x64 with GNU General Public License v3.0 6 votes vote down vote up
def sender(group):
    addrinfo = socket.getaddrinfo(group, None)[0]

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

    # Set Time-to-live (optional)
    ttl_bin = struct.pack('@i', MYTTL)
    if addrinfo[0] == socket.AF_INET: # IPv4
        s.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl_bin)
    else:
        s.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_HOPS, ttl_bin)

    while True:
        data = repr(time.time()).encode('utf-8') + b'\0'
        s.sendto(data, (addrinfo[4][0], MYPORT))
        time.sleep(1) 
Example #5
Source File: coap.py    From pyShelly with MIT License 6 votes vote down vote up
def _init_socket(self):
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM,
                             socket.IPPROTO_UDP)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 10)
        sock.bind((self._root.bind_ip, COAP_PORT))
        if self._root.host_ip:
            mreq = struct.pack("=4s4s",
                               socket.inet_aton(COAP_IP),
                               socket.inet_aton(self._root.host_ip))
        else:
            mreq = struct.pack("=4sl",
                               socket.inet_aton(COAP_IP),
                               socket.INADDR_ANY)
        sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
        sock.settimeout(15)
        self._socket = sock 
Example #6
Source File: wsdd.py    From wsdd with MIT License 6 votes vote down vote up
def init_v4(self):
        idx = socket.if_nametoindex(self.interface.name)
        self.multicast_address = (WSD_MCAST_GRP_V4, WSD_UDP_PORT)

        # v4: member_request (ip_mreqn) = { multicast_addr, intf_addr, idx }
        mreq = (
            socket.inet_pton(self.family, WSD_MCAST_GRP_V4) +
            socket.inet_pton(self.family, self.address) +
            struct.pack('@I', idx))
        self.recv_socket.setsockopt(
            socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)

        try:
            self.recv_socket.bind((WSD_MCAST_GRP_V4, WSD_UDP_PORT))
        except OSError:
            self.recv_socket.bind(('', WSD_UDP_PORT))

        self.send_socket.setsockopt(
            socket.IPPROTO_IP, socket.IP_MULTICAST_IF, mreq)
        self.send_socket.setsockopt(
            socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 0)
        self.send_socket.setsockopt(
            socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, args.hoplimit)

        self.listen_address = (self.address, WSD_HTTP_PORT) 
Example #7
Source File: roku.py    From netscan2 with MIT License 6 votes vote down vote up
def discover(service, timeout=5, retries=1, mx=3):
    group = (b"239.255.255.250", 1900)
    message = "\r\n".join([
        'M-SEARCH * HTTP/1.1',
        'HOST: {0}:{1}',
        'MAN: "ssdp:discover"',
        'ST: {st}',
        'MX: {mx}',
        '',
        ''])
    socket.setdefaulttimeout(timeout)
    responses = []
    for _ in range(retries):
        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.sendto(message.format(*group, st=service, mx=mx).encode('utf-8'), group)
        while True:
            try:
                resp = SSDPResponse(sock.recv(1024))
                # responses[resp.location] = resp
                responses.append(resp)
            except socket.timeout:
                break
    return responses 
Example #8
Source File: devices.py    From nano-dlna with MIT License 5 votes vote down vote up
def get_devices(timeout=3.0):

    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    s.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 4)
    s.bind(("", SSDP_BROADCAST_PORT + 10))

    s.sendto(SSDP_BROADCAST_MSG.encode("UTF-8"), (SSDP_BROADCAST_ADDR,
                                                  SSDP_BROADCAST_PORT))

    s.settimeout(timeout)

    devices = []
    while True:

        try:
            data, addr = s.recvfrom(1024)
        except socket.timeout:
            break

        try:
            info = [a.split(":", 1)
                    for a in data.decode("UTF-8").split("\r\n")[1:]]
            device = dict([(a[0].strip().lower(), a[1].strip())
                           for a in info if len(a) >= 2])
            devices.append(device)
        except Exception:
            pass

    devices_urls = [dev["location"]
                    for dev in devices if "AVTransport" in dev["st"]]
    devices = [register_device(location_url) for location_url in devices_urls]

    return devices 
Example #9
Source File: udp_multicast.py    From crazyswarm with MIT License 5 votes vote down vote up
def __init__(self, MCAST_GRP = '224.1.1.1', MCAST_PORT = 5007):
    self.MCAST_GRP = MCAST_GRP
    self.MCAST_PORT = MCAST_PORT
    self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2) 
Example #10
Source File: packetizer.py    From WaveSync with MIT License 5 votes vote down vote up
def create_socket(self, channels, ttl, multicast_loop, broadcast, source_address=None):
        "Create a UDP multicast socket"
        self.sock = socket.socket(socket.AF_INET,
                                  socket.SOCK_DGRAM,
                                  socket.IPPROTO_UDP)
        self.sock.setsockopt(socket.IPPROTO_IP,
                             socket.IP_MULTICAST_TTL,
                             ttl)

        for address, port in channels:
            if source_address and ipaddress.IPv4Address(address).is_multicast:
                try:
                    self.sock.setsockopt(socket.SOL_IP,
                                         socket.IP_MULTICAST_IF,
                                         socket.inet_aton(source_address))
                    print("added membership, interface source address: %s, group: %s" % (source_address, address))
                    self.sock.setsockopt(socket.SOL_IP,
                                         socket.IP_ADD_MEMBERSHIP,
                                         socket.inet_aton(address) + socket.inet_aton(source_address))
                except:
                    print("failed to add membership, interface source address: %s, group: %s. This is ok for unicast." % (source_address, address))

        if multicast_loop is True:
            self.sock.setsockopt(socket.IPPROTO_IP,
                                 socket.IP_MULTICAST_LOOP, 1)

        if broadcast is True:
            self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)

        self.destinations = [
            (address, port)
            for address, port in channels
        ]

        IP_PMTUDISC_DO = 2
        IP_MTU_DISCOVER = 10

        # Set DF flag on IP packet (Don't Fragment) - fragmenting would be bad idea
        # it's way better to chunk the packets right.
        self.sock.setsockopt(socket.IPPROTO_IP, IP_MTU_DISCOVER, IP_PMTUDISC_DO) 
Example #11
Source File: zeroconf.py    From RepetierIntegration with GNU Affero General Public License v3.0 5 votes vote down vote up
def new_socket():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    # 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.
    # Catch OSError and socket.error for kernel versions <3.9 because lacking
    # SO_REUSEPORT support.
    try:
        reuseport = socket.SO_REUSEPORT
    except AttributeError:
        pass
    else:
        try:
            s.setsockopt(socket.SOL_SOCKET, reuseport, 1)
        except (OSError, socket.error) as err:
            # OSError on python 3, socket.error on python 2
            if not err.errno == errno.ENOPROTOOPT:
                raise

    # OpenBSD needs the ttl and loop values for the IP_MULTICAST_TTL and
    # IP_MULTICAST_LOOP socket options as an unsigned char.
    ttl = struct.pack(b'B', 255)
    s.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl)
    loop = struct.pack(b'B', 1)
    s.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, loop)

    s.bind(('', _MDNS_PORT))
    return s 
Example #12
Source File: services.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def set_ipv4_multicast_source_address(sock, source_address):
    """Sets the given socket up to send multicast from the specified source.

    Ensures the multicast TTL is set to 1, so that packets are not forwarded
    beyond the local link.

    :param sock: An opened IP socket.
    :param source_address: A string representing an IPv4 source address.
    """
    sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 1)
    sock.setsockopt(
        socket.IPPROTO_IP,
        socket.IP_MULTICAST_IF,
        socket.inet_aton(source_address),
    ) 
Example #13
Source File: csruntime.py    From calvin-base with Apache License 2.0 5 votes vote down vote up
def discover(timeout=2, retries=5):
    import struct
    from calvin.runtime.south.storage.twistedimpl.dht.service_discovery_ssdp import SSDPServiceDiscovery,\
                                                                                            SERVICE_UUID,\
                                                                                            CA_SERVICE_UUID,\
                                                                                            SSDP_ADDR,\
                                                                                            SSDP_PORT,\
                                                                                            MS_CA
    _log.info("discover")
    message = MS_CA
    socket.setdefaulttimeout(timeout)
    responses = {}
    attempt=0
    while attempt in range(retries) and not bool(responses):
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        ttl = struct.pack('b', 1)
        sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl)
        try:
            sent = sock.sendto(message, (SSDP_ADDR,SSDP_PORT))
            while True:
                try:
                    data, server = sock.recvfrom(1000)
                except socket.timeout:
                    time.sleep(5)
                    break
                else:
                    responses[server] = data
                    _log.debug("Received {} from {}".format(data, server))
        finally:
            _log.debug("Closing socket")
            sock.close()
    return responses.values() 
Example #14
Source File: udp_server.py    From mmvt with GNU General Public License v3.0 5 votes vote down vote up
def bind_to_multicast():
    import struct
    # Create the datagram socket
    # sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    # Set a timeout so the socket does not block indefinitely when trying
    # to receive data.
    # sock.settimeout(0.2)
    # Set the time-to-live for messages to 1 so they do not go past the
    # local network segment.
    # ttl = struct.pack('b', 1)
    # sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl)
    sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
    return sock 
Example #15
Source File: multicast.py    From openhtf with Apache License 2.0 5 votes vote down vote up
def __init__(self,
               callback,
               address=DEFAULT_ADDRESS,
               port=DEFAULT_PORT,
               ttl=DEFAULT_TTL):
    super(MulticastListener, self).__init__()
    self.address = address
    self.port = port
    self.ttl = ttl
    self._callback = callback
    self._live = False
    self._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    self._sock.setsockopt(socket.IPPROTO_IP,
                          socket.IP_MULTICAST_TTL,
                          self.ttl) 
Example #16
Source File: udp.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def setTTL(self, ttl):
        ttl = struct.pack("B", ttl)
        self.socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl) 
Example #17
Source File: MDNS.py    From MITMf with GNU General Public License v3.0 5 votes vote down vote up
def server_bind(self):
		MADDR = "224.0.0.251"
		
		self.socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR, 1)
		self.socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 255)
		
		Join = self.socket.setsockopt(socket.IPPROTO_IP,socket.IP_ADD_MEMBERSHIP, socket.inet_aton(MADDR) + settings.Config.IP_aton)

		if OsInterfaceIsSupported():
			try:
				self.socket.setsockopt(socket.SOL_SOCKET, 25, settings.Config.Bind_To+'\0')
			except:
				pass
		UDPServer.server_bind(self) 
Example #18
Source File: ssdp.py    From pyOpenBCI with MIT License 5 votes vote down vote up
def discover(service, timeout=5, retries=1, mx=3, wifi_found_cb=None):
    group = ("239.255.255.250", 1900)
    message = "\r\n".join([
        'M-SEARCH * HTTP/1.1',
        'HOST: {0}:{1}',
        'MAN: "ssdp:discover"',
        'ST: {st}', 'MX: {mx}', '', ''])

    socket.setdefaulttimeout(timeout)
    responses = {}
    for _ in range(retries):
        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)
        sockMessage = message.format(*group, st=service, mx=mx)
        if pyVersion == 3:
            sockMessage = sockMessage.encode("utf-8")
        sock.sendto(sockMessage, group)
        while True:
            try:
                response = SSDPResponse(sock.recv(1024))
                if wifi_found_cb is not None:
                    wifi_found_cb(response)
                responses[response.location] = response
            except socket.timeout:
                break
    return list(responses.values()) 
Example #19
Source File: udp.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def setTTL(self, ttl):
        ttl = struct.pack("B", ttl)
        self.socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl) 
Example #20
Source File: discovery.py    From python-roku with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def discover(timeout=2, retries=1, st=ST_ECP):

    group = ("239.255.255.250", 1900)

    message = "\r\n".join(
        [
            "M-SEARCH * HTTP/1.1",
            "HOST: {0}:{1}".format(*group),
            'MAN: "ssdp:discover"',
            "ST: {st}",
            "MX: 3",
            "",
            "",
        ]
    )

    socket.setdefaulttimeout(timeout)

    responses = {}

    for _ in range(retries):
        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)

        m = message.format(st=st)
        sock.sendto(m.encode(), group)

        while 1:
            try:
                rhttp = HTTPResponse(_FakeSocket(sock.recv(1024)))
                rhttp.begin()
                if rhttp.status == 200:
                    rssdp = SSDPResponse(rhttp)
                    responses[rssdp.location] = rssdp
            except socket.timeout:
                break

    return responses.values() 
Example #21
Source File: udp.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def getTTL(self):
        return self.socket.getsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL) 
Example #22
Source File: LLMNR.py    From MITMf with GNU General Public License v3.0 5 votes vote down vote up
def server_bind(self):
        MADDR = "224.0.0.252"

        self.socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
        self.socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 255)
        
        Join = self.socket.setsockopt(socket.IPPROTO_IP,socket.IP_ADD_MEMBERSHIP,socket.inet_aton(MADDR) + settings.Config.IP_aton)
        
        if OsInterfaceIsSupported():
            try:
                self.socket.setsockopt(socket.SOL_SOCKET, 25, settings.Config.Bind_To+'\0')
            except:
                pass
        UDPServer.server_bind(self) 
Example #23
Source File: udp.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def getTTL(self):
        return self.socket.getsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL) 
Example #24
Source File: udp.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def setTTL(self, ttl):
        ttl = struct.pack("B", ttl)
        self.socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl) 
Example #25
Source File: udp.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def getTTL(self):
        return self.socket.getsockopt(socket.IPPROTO_IP,
                                      socket.IP_MULTICAST_TTL) 
Example #26
Source File: InverterLib.py    From Inverter-Data-Logger with GNU General Public License v3.0 5 votes vote down vote up
def getLoggers():
    # Create the datagram socket
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.bind((getNetworkIp(), 48899))
    # Set a timeout so the socket does not block indefinitely when trying to receive data.
    sock.settimeout(3)
    # Set the time-to-live for messages to 1 so they do not go past the local network segment.
    ttl = struct.pack('b', 1)
    sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
    SendData = "WIFIKIT-214028-READ" # Lotto/TM = "AT+YZAPP=214028,READ"

    gateways = ''
    try:
        # Send data to the broadcast address
        sent = sock.sendto(SendData, ('<broadcast>', 48899))
        # Look for responses from all recipients
        while True:
            try:
                data, server = sock.recvfrom(1024)
            except socket.timeout:
                break
            else:
                if (data == SendData): continue #skip sent data
                a = data.split(',')
                wifi_ip, wifi_mac, wifi_sn = a[0],a[1],a[2]
                if (len(gateways)>1):
                    gateways = gateways+','
                gateways = gateways+wifi_ip+','+wifi_sn

    finally:
        sock.close()
        return gateways 
Example #27
Source File: ssdp.py    From pyvizio with MIT License 5 votes vote down vote up
def discover(service, timeout=DEFAULT_TIMEOUT, retries=1, mx=3):
    """Return all discovered SSDP services of a given service name over given timeout period."""
    group = ("239.255.255.250", 1900)
    message = "\r\n".join(
        [
            "M-SEARCH * HTTP/1.1",
            "HOST: {0}:{1}",
            'MAN: "ssdp:discover"',
            "ST: {st}",
            "MX: {mx}",
            "",
            "",
        ]
    )
    socket.setdefaulttimeout(timeout)
    responses = {}
    for _ in range(retries):
        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)
        message_bytes = message.format(*group, st=service, mx=mx).encode("utf-8")
        sock.sendto(message_bytes, group)

        while True:
            try:
                response = SSDPResponse(sock.recv(1024))
                responses[response.location] = response
            except socket.timeout:
                break

        return list(responses.values()) 
Example #28
Source File: ssdp.py    From HomePWN with GNU General Public License v3.0 5 votes vote down vote up
def _get_sockets(self):
        sockets = []
        for addr in zeroconf.get_all_addresses():
            try:
                sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
                # Set the time-to-live for messages for local network
                sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL,
                                self.SSDP_MX)
                sock.bind((addr, 0))
                sockets.append(sock)
            except socket.error:
                pass
        
        return sockets 
Example #29
Source File: ssdp.py    From script.tubecast with MIT License 5 votes vote down vote up
def set_ttl(self, ttl):
        ttl = struct.pack("B", ttl)
        self.socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl) 
Example #30
Source File: discover.py    From Paradrop with Apache License 2.0 5 votes vote down vote up
def perform_ssdp_discovery(service, timeout=5, retries=5, mx=3):
    # Standard multicast IP address and port for SSDP.
    group = ("239.255.255.250", 1900)

    message = "\r\n".join([
        "M-SEARCH * HTTP/1.1",
        "HOST: {0}:{1}",
        'MAN: "ssdp:discover"',
        "ST: {st}",
        "MX: {mx}"
    ]).format(*group, st=service, mx=mx)

    socket.setdefaulttimeout(timeout)

    sources = set()
    for _ in range(retries):
        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.sendto(message.encode('utf-8'), group)
        while True:
            try:
                data, addr = sock.recvfrom(1024)
                response = SsdpResponse(data, addr)
                if addr[0] not in sources:
                    # We only want to return each node once.
                    sources.add(addr[0])
                    yield response
            except socket.timeout:
                break