Python socket.IPPROTO_UDP() Examples

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

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

Example 1
Project: rift-python   Author: brunorijsman   File: multicast_checks.py    License: Apache License 2.0 6 votes vote down vote up
def _create_ipv4_sockets(loopback_enabled):
    # Open a multicast send socket, with IP_MULTICAST_LOOP enabled or disabled as requested.
    mcast_address = "224.0.1.195"
    port = 49501
    group = (mcast_address, port)
    txsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    txsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    if loopback_enabled:
        txsock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 1)
    else:
        txsock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 0)
    txsock.connect(group)
    # Open a multicast receive socket and join the group
    rxsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    req = struct.pack("=4sl", socket.inet_aton(mcast_address), socket.INADDR_ANY)
    rxsock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, req)
    rxsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    rxsock.bind(group)
    return (txsock, rxsock) 
Example 2
Project: rift-python   Author: brunorijsman   File: multicast_checks.py    License: Apache License 2.0 6 votes vote down vote up
def _create_ipv6_sockets(loopback_enabled):
    # Open a multicast send socket, with IP_MULTICAST_LOOP enabled or disabled as requested.
    intf_name = find_ethernet_interface()
    intf_index = socket.if_nametoindex(intf_name)
    mcast_address = "ff02::abcd:99"
    port = 30000
    group = (mcast_address, port)
    txsock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    txsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    txsock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_IF, intf_index)
    if loopback_enabled:
        txsock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_LOOP, 1)
    else:
        txsock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_LOOP, 0)
    txsock.connect(group)
    # Open a multicast receive socket and join the group
    rxsock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    req = struct.pack("=16si", socket.inet_pton(socket.AF_INET6, mcast_address), intf_index)
    if platform.system() == "Darwin":
        rxsock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_JOIN_GROUP, req)
    else:
        rxsock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_ADD_MEMBERSHIP, req)
    rxsock.bind(("::", port))
    return (txsock, rxsock) 
Example 3
Project: rift-python   Author: brunorijsman   File: udp_rx_handler.py    License: Apache License 2.0 6 votes vote down vote up
def create_socket_ipv4_rx_ucast(self):
        if self._local_ipv4_address is None:
            self.warning("Could not create IPv4 UDP socket: don't have a local address")
            return None
        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._local_ipv4_address, self._local_port))
        except (IOError, OSError) as err:
            self.warning("Could not bind IPv4 UDP socket to address %s port %d: %s",
                         self._local_ipv4_address, self._local_port, err)
            return None
        try:
            sock.setblocking(0)
        except (IOError, OSError) as err:
            self.warning("Could set unicast receive IPv4 UDP to non-blocking mode: %s", err)
            return None
        return sock 
Example 4
Project: rift-python   Author: brunorijsman   File: interface.py    License: Apache License 2.0 6 votes vote down vote up
def create_socket_ipv6_tx_ucast(self, remote_address, port):
        try:
            sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        except IOError as err:
            self.warning("Could not create IPv6 UDP socket: %s", err)
            return None
        self.enable_addr_and_port_reuse(sock)
        try:
            sock_addr = socket.getaddrinfo(remote_address, port, socket.AF_INET6,
                                           socket.SOCK_DGRAM)[0][4]
            sock.connect(sock_addr)
        except IOError as err:
            self.warning("Could not connect UDP socket to address %s port %d: %s",
                         remote_address, port, err)
            return None
        return sock 
Example 5
Project: ros2cli   Author: ros2   File: __init__.py    License: Apache License 2.0 6 votes vote down vote up
def receive(*, group=DEFAULT_GROUP, port=DEFAULT_PORT, timeout=None):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    try:
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        try:
            s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
        except AttributeError:
            # not available on Windows
            pass
        s.bind(('', port))

        s.settimeout(timeout)

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

            self._socket.settimeout(timeout)

            self._mreq = struct.pack('4sl', socket.inet_aton(group), socket.INADDR_ANY)
            self._socket.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, self._mreq)
        except Exception:
            self._dummy_socket.close()
            self._socket.close()
            raise
        self._is_shutdown = False
        self._summary_table = summary_table
        self._group = group
        self._port = port 
Example 7
Project: networkzero   Author: tjguk   File: test_discovery.py    License: MIT License 6 votes vote down vote up
def test_beacon_already_running():
    #
    # NB this one has to run without the beacon fixture
    #
    # Bind a socket on a random port before attempting
    # to start a beacon on that same port.
    #
    port = random.choice(nw0.config.DYNAMIC_PORTS)
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
    s.bind(("", port))
    try:
        assert nw0.discovery._beacon is None
        nw0.discovery._start_beacon(port=port)
        assert nw0.discovery._beacon is nw0.discovery._remote_beacon
    finally:
        s.close()
        #
        # Make sure any future beacon use assumes it's not
        # already running.
        #
        nw0.discovery._stop_beacon() 
Example 8
Project: CyberScan   Author: medbenali   File: inet.py    License: GNU General Public License v3.0 6 votes vote down vote up
def post_build(self, p, pay):
        p += pay
        l = self.len
        if l is None:
            l = len(p)
            p = p[:4]+struct.pack("!H",l)+p[6:]
        if self.chksum is None:
            if isinstance(self.underlayer, IP):
                if self.underlayer.len is not None:
                    ln = self.underlayer.len-20
                else:
                    ln = len(p)
                psdhdr = struct.pack("!4s4sHH",
                                     inet_aton(self.underlayer.src),
                                     inet_aton(self.underlayer.dst),
                                     self.underlayer.proto,
                                     ln)
                ck=checksum(psdhdr+p)
                p = p[:6]+struct.pack("!H", ck)+p[8:]
            elif isinstance(self.underlayer, scapy.layers.inet6.IPv6) or isinstance(self.underlayer, scapy.layers.inet6._IPv6ExtHdr):
                ck = scapy.layers.inet6.in6_chksum(socket.IPPROTO_UDP, self.underlayer, p)
                p = p[:6]+struct.pack("!H", ck)+p[8:]
            else:
                warning("No IP underlayer to compute checksum. Leaving null.")
        return p 
Example 9
Project: Nscan   Author: OffensivePython   File: probe.py    License: Apache License 2.0 6 votes vote down vote up
def __init__(self, options):
		self.options = options
		self.hosts = self.split(options.hosts, options.threads)
		self.ports = options.ports
		self.srcp = random.randint(1, 65535)#self.PickPort() # source port
		self.smac = options.smac
		self.dmac = options.dmac
		self.ifname = options.ifname
		self.siface = options.siface
		self.diface = options.diface
		self.banner = options.banner
		self.count = options.count
		self.cooldown = options.cooldown
		self.queue = Queue.Queue()
		if options.stype.upper()=='U':
			self.stype = socket.IPPROTO_UDP
		else:
			self.stype = socket.IPPROTO_TCP
		self.events = {
			'send': threading.Event(),
			'recv': threading.Event()}
		self.threads = {
			'send': [],
			'recv': None} 
Example 10
Project: smod-1   Author: theralfbrown   File: inet.py    License: GNU General Public License v2.0 6 votes vote down vote up
def post_build(self, p, pay):
        p += pay
        l = self.len
        if l is None:
            l = len(p)
            p = p[:4]+struct.pack("!H",l)+p[6:]
        if self.chksum is None:
            if isinstance(self.underlayer, IP):
                if self.underlayer.len is not None:
                    ln = self.underlayer.len-20
                else:
                    ln = len(p)
                psdhdr = struct.pack("!4s4sHH",
                                     inet_aton(self.underlayer.src),
                                     inet_aton(self.underlayer.dst),
                                     self.underlayer.proto,
                                     ln)
                ck=checksum(psdhdr+p)
                p = p[:6]+struct.pack("!H", ck)+p[8:]
            elif isinstance(self.underlayer, scapy.layers.inet6.IPv6) or isinstance(self.underlayer, scapy.layers.inet6._IPv6ExtHdr):
                ck = scapy.layers.inet6.in6_chksum(socket.IPPROTO_UDP, self.underlayer, p)
                p = p[:6]+struct.pack("!H", ck)+p[8:]
            else:
                warning("No IP underlayer to compute checksum. Leaving null.")
        return p 
Example 11
Project: CVE-2016-6366   Author: RiskSense-Ops   File: inet.py    License: MIT License 6 votes vote down vote up
def post_build(self, p, pay):
        p += pay
        l = self.len
        if l is None:
            l = len(p)
            p = p[:4]+struct.pack("!H",l)+p[6:]
        if self.chksum is None:
            if isinstance(self.underlayer, IP):
                if self.underlayer.len is not None:
                    ln = self.underlayer.len-20
                else:
                    ln = len(p)
                psdhdr = struct.pack("!4s4sHH",
                                     inet_aton(self.underlayer.src),
                                     inet_aton(self.underlayer.dst),
                                     self.underlayer.proto,
                                     ln)
                ck=checksum(psdhdr+p)
                p = p[:6]+struct.pack("!H", ck)+p[8:]
            elif isinstance(self.underlayer, scapy.layers.inet6.IPv6) or isinstance(self.underlayer, scapy.layers.inet6._IPv6ExtHdr):
                ck = scapy.layers.inet6.in6_chksum(socket.IPPROTO_UDP, self.underlayer, p)
                p = p[:6]+struct.pack("!H", ck)+p[8:]
            else:
                warning("No IP underlayer to compute checksum. Leaving null.")
        return p 
Example 12
Project: mptcp-abuse   Author: Neohapsis   File: inet.py    License: GNU General Public License v2.0 6 votes vote down vote up
def post_build(self, p, pay):
        p += pay
        l = self.len
        if l is None:
            l = len(p)
            p = p[:4]+struct.pack("!H",l)+p[6:]
        if self.chksum is None:
            if isinstance(self.underlayer, IP):
                if self.underlayer.len is not None:
                    ln = self.underlayer.len-20
                else:
                    ln = len(p)
                psdhdr = struct.pack("!4s4sHH",
                                     inet_aton(self.underlayer.src),
                                     inet_aton(self.underlayer.dst),
                                     self.underlayer.proto,
                                     ln)
                ck=checksum(psdhdr+p)
                p = p[:6]+struct.pack("!H", ck)+p[8:]
            elif isinstance(self.underlayer, scapy.layers.inet6.IPv6) or isinstance(self.underlayer, scapy.layers.inet6._IPv6ExtHdr):
                ck = scapy.layers.inet6.in6_chksum(socket.IPPROTO_UDP, self.underlayer, p)
                p = p[:6]+struct.pack("!H", ck)+p[8:]
            else:
                warning("No IP underlayer to compute checksum. Leaving null.")
        return p 
Example 13
Project: scapy   Author: secdev   File: inet.py    License: GNU General Public License v2.0 6 votes vote down vote up
def post_build(self, p, pay):
        p += pay
        tmp_len = self.len
        if tmp_len is None:
            tmp_len = len(p)
            p = p[:4] + struct.pack("!H", tmp_len) + p[6:]
        if self.chksum is None:
            if isinstance(self.underlayer, IP):
                ck = in4_chksum(socket.IPPROTO_UDP, self.underlayer, p)
                # According to RFC768 if the result checksum is 0, it should be set to 0xFFFF  # noqa: E501
                if ck == 0:
                    ck = 0xFFFF
                p = p[:6] + struct.pack("!H", ck) + p[8:]
            elif isinstance(self.underlayer, scapy.layers.inet6.IPv6) or isinstance(self.underlayer, scapy.layers.inet6._IPv6ExtHdr):  # noqa: E501
                ck = scapy.layers.inet6.in6_chksum(socket.IPPROTO_UDP, self.underlayer, p)  # noqa: E501
                # According to RFC2460 if the result checksum is 0, it should be set to 0xFFFF  # noqa: E501
                if ck == 0:
                    ck = 0xFFFF
                p = p[:6] + struct.pack("!H", ck) + p[8:]
            else:
                warning("No IP underlayer to compute checksum. Leaving null.")
        return p 
Example 14
Project: snippet   Author: xgfone   File: startCrawler.py    License: MIT License 6 votes vote down vote up
def __init__(self, master, bind_ip, bind_port, max_node_qsize):
        DHTClient.__init__(self, max_node_qsize)

        self.master = master
        self.bind_ip = bind_ip
        self.bind_port = bind_port
        self.speed = 0

        self.process_request_actions = {
            "get_peers": self.on_get_peers_request,
            "announce_peer": self.on_announce_peer_request,
        }

        self.ufd = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        self.ufd.bind((self.bind_ip, self.bind_port))

        timer(RE_JOIN_DHT_INTERVAL, self.re_join_DHT) 
Example 15
Project: snippet   Author: xgfone   File: simdt_worker.py    License: MIT License 6 votes vote down vote up
def __init__(self, master, bind_ip, bind_port, max_node_qsize):
        DHTClient.__init__(self, max_node_qsize)

        self.master = master
        self.bind_ip = bind_ip
        self.bind_port = bind_port

        self.process_request_actions = {
            "get_peers": self.on_get_peers_request,
            "announce_peer": self.on_announce_peer_request,
        }

        self.ufd = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        self.ufd.bind((self.bind_ip, self.bind_port))

        timer(RE_JOIN_DHT_INTERVAL, self.re_join_DHT) 
Example 16
Project: iptvtools   Author: huxuan   File: utils.py    License: MIT License 6 votes vote down vote up
def check_udp_connectivity(url, timeout=None):
    """Check UDP connectivity."""
    ipaddr, port = url.rsplit(':', 1)
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    sock.settimeout(timeout)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
    sock.bind(('', int(port)))
    mreq = struct.pack("4sl", socket.inet_aton(ipaddr), socket.INADDR_ANY)
    sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
    try:
        if sock.recv(10240):
            return True
    except socket.timeout:
        pass
    return False 
Example 17
Project: L-Spider   Author: LEXUGE   File: dht_spider.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def __init__(self, master, ip, port, max_node_qsize):
        Thread.__init__(self)
        self.setDaemon(True)

        self.max_node_qsize = max_node_qsize
        self.nid = random_id()
        self.nodes = deque(maxlen=max_node_qsize)

        self.master = master
        self.ip = ip
        self.port = port

        self.process_request_actions = {
            "get_peers": self.on_get_peers_request,
            "announce_peer": self.on_announce_peer_request,
        }

        self.ufd = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        self.ufd.bind((self.ip, self.port))

        timer(RE_JOIN_DHT_INTERVAL, self.re_join_DHT) 
Example 18
Project: ironpython3   Author: IronLanguages   File: test_base_events.py    License: Apache License 2.0 6 votes vote down vote up
def test_create_datagram_endpoint_ip_addr(self, m_socket):
        def getaddrinfo(*args, **kw):
            self.fail('should not have called getaddrinfo')

        m_socket.getaddrinfo = getaddrinfo
        m_socket.socket.return_value.bind = bind = mock.Mock()
        self.loop.add_reader = mock.Mock()
        self.loop.add_reader._is_coroutine = False

        reuseport_supported = hasattr(socket, 'SO_REUSEPORT')
        coro = self.loop.create_datagram_endpoint(
            lambda: MyDatagramProto(loop=self.loop),
            local_addr=('1.2.3.4', 0),
            reuse_address=False,
            reuse_port=reuseport_supported)

        t, p = self.loop.run_until_complete(coro)
        try:
            bind.assert_called_with(('1.2.3.4', 0))
            m_socket.socket.assert_called_with(family=m_socket.AF_INET,
                                               proto=m_socket.IPPROTO_UDP,
                                               type=m_socket.SOCK_DGRAM)
        finally:
            t.close()
            test_utils.run_briefly(self.loop)  # allow transport to close 
Example 19
Project: PyXiaomiGateway   Author: Danielhiversen   File: __init__.py    License: MIT License 6 votes vote down vote up
def _create_mcast_socket(self):
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

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

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

        sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
        return sock 
Example 20
Project: PyXiaomiGateway   Author: Danielhiversen   File: gateway.py    License: MIT License 6 votes vote down vote up
def __init__(self, config, event_loop):
        main_protocol = MainProtocol(config)
        task = event_loop.create_datagram_endpoint(lambda: main_protocol,
                                                   local_addr=(config['ip'], 9898))
        asyncio.ensure_future(task, loop=event_loop)
        sock = socket.socket(
            socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.bind(('224.0.0.50', 4321))
        mreq = socket.inet_aton('224.0.0.50') + socket.inet_aton(config['ip'])
        sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
        discovery_protocol = DiscoveryProtocol(config, main_protocol)
        task = event_loop.create_datagram_endpoint(lambda: discovery_protocol,
                                                   sock=sock)
        asyncio.ensure_future(task, loop=event_loop)
        self.discovery_protocol = discovery_protocol
        self.main_protocol = main_protocol 
Example 21
Project: pyShelly   Author: StyraHem   File: coap.py    License: MIT License 6 votes vote down vote up
def _init_socket(self):
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM,
                             socket.IPPROTO_UDP)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 10)
        sock.bind((self._root.bind_ip, COAP_PORT))
        if self._root.host_ip:
            mreq = struct.pack("=4s4s",
                               socket.inet_aton(COAP_IP),
                               socket.inet_aton(self._root.host_ip))
        else:
            mreq = struct.pack("=4sl",
                               socket.inet_aton(COAP_IP),
                               socket.INADDR_ANY)
        sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
        sock.settimeout(15)
        self._socket = sock 
Example 22
Project: tripleo-validations   Author: openstack   File: rogue_dhcp.py    License: Apache License 2.0 6 votes vote down vote up
def inspect_frame(data):
    eth_type = struct.unpack('!H', data[12:14])[0]
    protocol = data[23] if six.PY3 else ord(data[23])
    src_port = struct.unpack('!H', data[34:36])[0]
    dst_port = struct.unpack('!H', data[36:38])[0]
    msg_type = data[42] if six.PY3 else ord(data[42])
    # Make sure we got a DHCP Offer
    if eth_type == ETH_P_IP \
            and protocol == socket.IPPROTO_UDP \
            and src_port == 67 \
            and dst_port == 68 \
            and msg_type == 2:  # DHCP Boot Reply
        if six.PY3:
            server_ip_address = '.'.join(["%s" % m for m in
                                         data[26:30]])
            server_hw_address = ":".join(["%02x" % m for m in
                                         data[6:12]])
        else:
            server_ip_address = '.'.join(["%s" % ord(m) for m in
                                         data[26:30]])
            server_hw_address = ":".join(["%02x" % ord(m) for m in
                                         data[6:12]])
        dhcp_servers.append([server_ip_address, server_hw_address]) 
Example 23
Project: Paradrop   Author: ParadropLabs   File: discover.py    License: 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 
Example 24
Project: multicast-relay   Author: alsmith   File: ssdpDiscover.py    License: GNU General Public License v3.0 5 votes vote down vote up
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--ifAddr', help='Send out on the interface with the given address.')
    args = parser.parse_args()

    msearch = 'M-SEARCH * HTTP/1.1\r\n' \
              'HOST:239.255.255.250:1900\r\n' \
              'ST:upnp:rootdevice\r\n' \
              'MX:2\r\n' \
              'MAN:"ssdp:discover"\r\n' \
              '\r\n'

    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    if args.ifAddr:
        s.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_IF, socket.inet_aton(args.ifAddr))

    s.settimeout(2)
    s.sendto(msearch.encode('utf-8'), ('239.255.255.250', 1900))

    try:
        while True:
            data, addr = s.recvfrom(65535)
            try:
                print('%s [%s]' % (socket.gethostbyaddr(addr[0])[0], addr[0]))
            except socket.herror:
                print(addr[0])
            print(data)
    except socket.timeout:
        pass 
Example 25
Project: multicast-relay   Author: alsmith   File: multicast-relay.py    License: 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.
            if interface not in self.noTransmitInterfaces:
                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 26
Project: rift-python   Author: brunorijsman   File: udp_rx_handler.py    License: Apache License 2.0 5 votes vote down vote up
def create_socket_ipv4_rx_mcast(self):
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        except (IOError, OSError) as err:
            self.warning("Could not create IPv4 UDP socket: %s", err)
            return None
        self.enable_addr_and_port_reuse(sock)
        try:
            sock.bind((self._multicast_address, self._local_port))
        except (IOError, OSError) as err:
            self.warning("Could not bind IPv4 UDP socket to address %s port %d: %s",
                         self._multicast_address, self._local_port, err)
            return None
        if sock is None:
            return None
        if self._local_ipv4_address:
            req = struct.pack("=4s4s", socket.inet_aton(self._multicast_address),
                              socket.inet_aton(self._local_ipv4_address))
        else:
            req = struct.pack("=4sl", socket.inet_aton(self._multicast_address), socket.INADDR_ANY)
        try:
            sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, req)
        except (IOError, OSError) as err:
            self.warning("Could not join IPv4 group %s for local address %s: %s",
                         self._multicast_address, self._local_ipv4_address, err)
            return None
        if not MACOS:
            try:
                # pylint:disable=no-member
                sock.setsockopt(socket.IPPROTO_IP, socket.IP_PKTINFO, 1)
            except (IOError, OSError) as err:
                # Warn, but keep going; this socket option is not supported on macOS
                self.warning("Could not set IP_PKTINFO socket option: %s", err)
        try:
            sock.setblocking(0)
        except (IOError, OSError) as err:
            self.warning("Could set multicast receive IPv4 UDP to non-blocking mode: %s", err)
            return None
        return sock 
Example 27
Project: rift-python   Author: brunorijsman   File: udp_rx_handler.py    License: Apache License 2.0 5 votes vote down vote up
def create_socket_ipv6_rx_ucast(self):
        if self._local_ipv6_address is None:
            self.warning("Could not create IPv6 UDP socket: don't have a local address")
            return None
        try:
            sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        except (IOError, OSError) as err:
            self.warning("Could not create IPv6 UDP socket: %s", err)
            return None
        self.enable_addr_and_port_reuse(sock)
        try:
            sockaddr = socket.getaddrinfo(self._local_ipv6_address,
                                          self._local_port,
                                          socket.AF_INET6,
                                          socket.SOCK_DGRAM)[0][4]
            sock.bind(sockaddr)
        except (IOError, OSError) as err:
            self.warning("Could not bind IPv6 UDP socket to address %s port %d: %s",
                         self._local_ipv6_address, self._local_port, err)
            return None
        try:
            sock.setblocking(0)
        except (IOError, OSError) as err:
            self.warning("Could set unicast receive IPv6 UDP to non-blocking mode: %s", err)
            return None
        return sock 
Example 28
Project: rift-python   Author: brunorijsman   File: interface.py    License: Apache License 2.0 5 votes vote down vote up
def create_socket_ipv4_tx_mcast(self, multicast_address, port, loopback):
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        except IOError as err:
            self.warning("Could not create IPv4 UDP socket: %s", err)
            return None
        self.enable_addr_and_port_reuse(sock)
        if self._ipv4_address is not None:
            try:
                sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_IF,
                                socket.inet_aton(self._ipv4_address))
            except IOError as err:
                self.warning("Could not set IPv6 multicast interface address %s: %s",
                             self._ipv4_address, err)
                return None
        try:
            loop_value = 1 if loopback else 0
            sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, loop_value)
        except IOError as err:
            self.warning("Could not set IPv4 multicast loopback value %d: %s", loop_value, err)
            return None
        try:
            sock.connect((multicast_address, port))
        except IOError as err:
            self.warning("Could not connect UDP socket to address %s port %d: %s",
                         multicast_address, port, err)
            return None
        return sock 
Example 29
Project: rift-python   Author: brunorijsman   File: interface.py    License: Apache License 2.0 5 votes vote down vote up
def create_socket_ipv4_tx_ucast(self, remote_address, port):
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        except IOError as err:
            self.warning("Could not create IPv4 UDP socket: %s", err)
            return None
        self.enable_addr_and_port_reuse(sock)
        try:
            sock.connect((remote_address, port))
        except IOError as err:
            self.warning("Could not connect UDP socket to address %s port %d: %s",
                         remote_address, port, err)
            return None
        return sock 
Example 30
Project: rift-python   Author: brunorijsman   File: interface.py    License: Apache License 2.0 5 votes vote down vote up
def create_socket_ipv6_tx_mcast(self, multicast_address, port, loopback):
        if self._interface_index is None:
            self.warning("Could not create IPv6 multicast TX socket: unknown interface index")
            return None
        try:
            sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        except IOError as err:
            self.warning("Could not create IPv6 UDP socket: %s", err)
            return None
        self.enable_addr_and_port_reuse(sock)
        try:
            sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_IF, self._interface_index)
        except IOError as err:
            self.warning("Could not set IPv6 multicast interface index %d: %s",
                         self._interface_index, err)
            return None
        try:
            loop_value = 1 if loopback else 0
            sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_LOOP, loop_value)
        except IOError as err:
            self.warning("Could not set IPv6 multicast loopback value %d: %s", loop_value, err)
            return None
        try:
            scoped_ipv6_multicast_address = (
                str(multicast_address) + '%' + self.physical_interface_name)
            sock_addr = socket.getaddrinfo(scoped_ipv6_multicast_address, port,
                                           socket.AF_INET6, socket.SOCK_DGRAM)[0][4]
            sock.connect(sock_addr)
        except (IOError, OSError) as err:
            self.warning("Could not connect UDP socket to address %s port %d: %s",
                         scoped_ipv6_multicast_address, port, err)
            return None
        return sock 
Example 31
Project: movistartv2xmltv   Author: ese   File: tva.py    License: GNU General Public License v2.0 5 votes vote down vote up
def getfiles(self):
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.settimeout(3)
        sock.bind((self.mcast_grp, self.mcast_port))
        mreq = struct.pack("=4sl", socket.inet_aton(self.mcast_grp), socket.INADDR_ANY)
        sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
        loop = True
        chunk = {}
        chunk["end"] = 0
	N = 335
        #Wait for an end chunk to start by the beginning
        while not (chunk["end"]):
            chunk = self._getchunk(sock)
            firstfile = str(chunk["filetype"])+"_"+str(chunk["fileid"])
        #Loop until firstfile
        while (loop):
                xmldata=""
                chunk = self._getchunk(sock)
                #Discard headers
                body=chunk["data"]
                while not (chunk["end"]):
                        xmldata+=body
                        chunk = self._getchunk(sock)
                        body=chunk["data"]
                #Discard last 4bytes binary footer?
                xmldata+=body[:-4]
                self._files[str(chunk["filetype"])+"_"+str(chunk["fileid"])]=xmldata
		N = N - 1
                if (str(chunk["filetype"])+"_"+str(chunk["fileid"]) == firstfile or N == 0):
                    loop = False
        sock.close() 
Example 32
Project: vulscan   Author: vulscanteam   File: packet.py    License: MIT License 5 votes vote down vote up
def pack(self, src, dst, proto=socket.IPPROTO_UDP):
        length = self.length + len(self.payload)
        pseudo_header = struct.pack(
            '!4s4sBBH',
            socket.inet_aton(src), socket.inet_aton(dst), 0,
            proto, length
        )
        self.checksum = checksum(pseudo_header)
        packet = struct.pack('!HHHH', self.src, self.dst, length, 0)
        return packet 
Example 33
Project: pulseaudio-dlna   Author: masmu   File: discover.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _search(self, host, ssdp_ttl, ssdp_mx, ssdp_amount):
        logger.debug('Binding socket to "{}" ...'.format(host or ''))
        sock = socket.socket(
            socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        sock.settimeout(ssdp_mx)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.setsockopt(
            socket.IPPROTO_IP,
            socket.IP_MULTICAST_TTL,
            ssdp_ttl)
        sock.bind((host, self.MSEARCH_PORT))

        for i in range(1, ssdp_amount + 1):
            t = threading.Timer(
                float(i) / 2, self._send_discover, args=[sock, ssdp_mx])
            t.start()

        while True:
            try:
                header, address = sock.recvfrom(self.BUFFER_SIZE)
                if self.cb_on_device_response:
                    guess = chardet.detect(header)
                    header = header.decode(guess['encoding'])
                    header = pulseaudio_dlna.plugins.dlna.ssdp._get_header_map(
                        header)
                    self.cb_on_device_response(header, address)
            except socket.timeout:
                break
        sock.close() 
Example 34
Project: goodbye-mihome   Author: aluminiumgeek   File: yeelight.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def discover():
    from mihome import MULTICAST, SOCKET_BUFSIZE

    # Empty stored list
    store.delete(STORE_KEY)

    address, port = MULTICAST.get('yeelight')
    yee_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    yee_socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 32)
    yee_socket.sendto('\r\n'.join(YEE_DISCOVER).encode(), (address, port))
    
    while True:
        data, _ = yee_socket.recvfrom(SOCKET_BUFSIZE)
        add_device(get_data(data.decode())) 
Example 35
Project: ros2cli   Author: ros2   File: __init__.py    License: Apache License 2.0 5 votes vote down vote up
def send(data, *, group=DEFAULT_GROUP, port=DEFAULT_PORT, ttl=None):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    if ttl is not None:
        packed_ttl = struct.pack('b', ttl)
        s.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, packed_ttl)
    try:
        s.sendto(data, (group, port))
    finally:
        s.close() 
Example 36
Project: ros2cli   Author: ros2   File: hello.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, summary_table, group=DEFAULT_GROUP, port=DEFAULT_PORT, ttl=None):
        self._socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        try:
            if ttl is not None:
                packed_ttl = struct.pack('b', ttl)
                self._socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, packed_ttl)
        except Exception:
            self._socket.close()
            raise
        self._summary_table = summary_table
        self._group = group
        self._port = port 
Example 37
Project: HomeAssistant_Components   Author: charleyzhu   File: dlna.py    License: Apache License 2.0 5 votes vote down vote up
def discover_MediaPlayer(self):
        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 + 20))

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

        s.settimeout(5.0)

        devices = []

        while True:

            try:
                data, addr = s.recvfrom(self.SOCKET_BUFSIZE)
                if len(data) is None:
                    continue

            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:
                pass

        devices_urls = [device["location"] for device in devices if "AVTransport" in device["st"]]
        devices_urls = list(set(devices_urls))
        devices = []
        for location_url in devices_urls:
            device = self.register_device(location_url)
            if device != None:
                devices.append(device)

        return devices 
Example 38
Project: SMA-EM   Author: datenschuft   File: sma-daemon.py    License: 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)
				emparts=decode_speedwire(sock.recv(608))
				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 39
Project: Nscan   Author: OffensivePython   File: probe.py    License: Apache License 2.0 5 votes vote down vote up
def __CookieCheck(self, data):
		check = False
		dstp = struct.unpack('!H', data[22:24])[0]
		if self.stype==socket.IPPROTO_UDP:
			if dstp==self.srcp:
				check = True
		else:
			ackn = struct.unpack('!L', data[28:32])[0]
			flags = struct.unpack('B', data[33])[0] & 0b010010 # SYN-ACK
			if dstp==self.srcp and ackn==0xDEADC0DF and flags==18:
				check = True
		return check 
Example 40
Project: Nscan   Author: OffensivePython   File: udp.py    License: Apache License 2.0 5 votes vote down vote up
def pack(self, src, dst, proto=socket.IPPROTO_UDP):
        length = self.length + len(self.payload)
        pseudo_header = struct.pack('!4s4sBBH', src, dst, 0, 
            proto, length)
        self.checksum = checksum(pseudo_header)
        packet = struct.pack('!HHHH',
            self.srcp, self.dstp, length, 0)
        return packet 
Example 41
Project: vlcp   Author: hubo1016   File: ofpmanager.py    License: Apache License 2.0 5 votes vote down vote up
def getconnectionsbyendpointname(self, name, vhost = '', timeout = 30):
        "Get connection by endpoint name (Domain name, IP or IPv6 address)"
        # Resolve the name
        if not name:
            endpoint = ''
            return await self.getconnectionbyendpoint(endpoint, vhost)
        else:
            request = (name, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, socket.IPPROTO_TCP, socket.AI_ADDRCONFIG | socket.AI_V4MAPPED)
            # Resolve hostname
            await self.apiroutine.wait_for_send(ResolveRequestEvent(request))
            timeout_, ev, m = await self.apiroutine.wait_with_timeout(timeout, ResolveResponseEvent.createMatcher(request))
            if timeout_:
                # Resolve is only allowed through asynchronous resolver
                #try:
                #    self.addrinfo = socket.getaddrinfo(self.hostname, self.port, socket.AF_UNSPEC, socket.SOCK_DGRAM if self.udp else socket.SOCK_STREAM, socket.IPPROTO_UDP if self.udp else socket.IPPROTO_TCP, socket.AI_ADDRCONFIG|socket.AI_NUMERICHOST)
                #except:
                raise IOError('Resolve hostname timeout: ' + name)
            else:
                if hasattr(ev, 'error'):
                    raise IOError('Cannot resolve hostname: ' + name)
                resp = ev.response
                for r in resp:
                    raddr = r[4]
                    if isinstance(raddr, tuple):
                        # Ignore port
                        endpoint = raddr[0]
                    else:
                        # Unix socket? This should not happen, but in case...
                        endpoint = raddr
                    r = await self.getconnectionsbyendpoint(endpoint, vhost)
                    if r is not None:
                        return r
            return None 
Example 42
Project: vlcp   Author: hubo1016   File: ovsdbmanager.py    License: Apache License 2.0 5 votes vote down vote up
def getconnectionsbyendpointname(self, name, vhost = '', timeout = 30):
        "Get connection by endpoint name (Domain name, IP or IPv6 address)"
        # Resolve the name
        if not name:
            endpoint = ''
            return await self.getconnectionbyendpoint(endpoint, vhost)
        else:
            request = (name, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, socket.IPPROTO_TCP, socket.AI_ADDRCONFIG | socket.AI_V4MAPPED)
            # Resolve hostname
            await self.apiroutine.wait_for_send(ResolveRequestEvent(request))
            timeout_, ev, _ = await self.apiroutine.wait_with_timeout(timeout, ResolveResponseEvent.createMatcher(request))
            if timeout_:
                # Resolve is only allowed through asynchronous resolver
                #try:
                #    self.addrinfo = socket.getaddrinfo(self.hostname, self.port, socket.AF_UNSPEC, socket.SOCK_DGRAM if self.udp else socket.SOCK_STREAM, socket.IPPROTO_UDP if self.udp else socket.IPPROTO_TCP, socket.AI_ADDRCONFIG|socket.AI_NUMERICHOST)
                #except:
                raise IOError('Resolve hostname timeout: ' + name)
            else:
                if hasattr(ev, 'error'):
                    raise IOError('Cannot resolve hostname: ' + name)
                resp = ev.response
                for r in resp:
                    raddr = r[4]
                    if isinstance(raddr, tuple):
                        # Ignore port
                        endpoint = raddr[0]
                    else:
                        # Unix socket? This should not happen, but in case...
                        endpoint = raddr
                    r = await self.getconnectionsbyendpoint(endpoint, vhost)
                    if r is not None:
                        return r 
Example 43
Project: taketv   Author: SVelizDonoso   File: taketv.py    License: MIT License 5 votes vote down vote up
def _send_udp(to, packet):
   sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
   sock.sendto(packet.encode(), to)
   yield sock
   sock.close() 
Example 44
Project: OpenBCI_Python   Author: openbci-archive   File: ssdp.py    License: 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 45
Project: NintendoClients   Author: Kinnay   File: socket.py    License: MIT License 5 votes vote down vote up
def __init__(self, sock=None):
		self.s = sock
		if not self.s:
			sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
			sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, True)
			self.s = SocketWrapper(sock) 
Example 46
Project: NintendoClients   Author: Kinnay   File: socket.py    License: MIT License 5 votes vote down vote up
def __init__(self, sock=None):
		self.s = sock
		if not self.s:
			sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
			self.s = SocketWrapper(sock) 
Example 47
Project: NintendoClients   Author: Kinnay   File: socket.py    License: MIT License 5 votes vote down vote up
def __init__(self, sock=None):
		self.s = sock
		if not self.s:
			sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
			self.s = SocketWrapper(sock)
		
		self.incoming = []
		self.clients = {} 
Example 48
Project: MicroDNSSrv   Author: jczic   File: microDNSSrv.py    License: MIT License 5 votes vote down vote up
def Start(self) :
        if not self._started :
            self._server = socket.socket( socket.AF_INET,
                                          socket.SOCK_DGRAM,
                                          socket.IPPROTO_UDP )
            self._server.setsockopt( socket.SOL_SOCKET,
                                     socket.SO_REUSEADDR,
                                     1 )
            self._server.bind(('0.0.0.0', 53))
            self._server.setblocking(True)
            return MicroDNSSrv._tryStartThread(self._serverProcess)
        return False

    # ---------------------------------------------------------------------------- 
Example 49
Project: AlexaControlledSamsungTV   Author: eclair4151   File: ssdp.py    License: MIT License 5 votes vote down vote up
def discover(service, timeout=5, retries=1, mx=3):
    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 50
Project: dnxfirewall-cmd   Author: DOWRIGHTTV   File: dns_proxy.py    License: GNU General Public License v3.0 5 votes vote down vote up
def listener_sock(self):
        l_sock = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.IPPROTO_UDP)
        l_sock.bind((self._intf, 3))

        return l_sock 
Example 51
Project: pysc2   Author: deepmind   File: lan_sc2_env.py    License: Apache License 2.0 5 votes vote down vote up
def udp_server(addr):
  family = socket.AF_INET6 if ":" in addr.ip else socket.AF_INET
  sock = socket.socket(family, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
  sock.bind(addr)
  return sock 
Example 52
Project: dlnap   Author: cherezov   File: dlnap.py    License: MIT License 5 votes vote down vote up
def _send_udp(to, packet):
   """ Send UDP message to group

   to -- (host, port) group to send the packet to
   packet -- message to send
   """
   sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
   sock.sendto(packet.encode(), to)
   yield sock
   sock.close() 
Example 53
Project: ironpython3   Author: IronLanguages   File: test_base_events.py    License: Apache License 2.0 5 votes vote down vote up
def mock_socket_module():
    m_socket = mock.MagicMock(spec=socket)
    for name in (
        'AF_INET', 'AF_INET6', 'AF_UNSPEC', 'IPPROTO_TCP', 'IPPROTO_UDP',
        'SOCK_STREAM', 'SOCK_DGRAM', 'SOL_SOCKET', 'SO_REUSEADDR', 'inet_pton'
    ):
        if hasattr(socket, name):
            setattr(m_socket, name, getattr(socket, name))
        else:
            delattr(m_socket, name)

    m_socket.socket = mock.MagicMock()
    m_socket.socket.return_value = test_utils.mock_nonblocking_socket()

    return m_socket 
Example 54
Project: ironpython3   Author: IronLanguages   File: test__socket.py    License: Apache License 2.0 5 votes vote down vote up
def test_getprotobyname(self):
        '''Tests _socket.getprotobyname'''
        #IP and CPython
        proto_map = {
                    "icmp": _socket.IPPROTO_ICMP,
                    "ip": _socket.IPPROTO_IP,
                    "tcp": _socket.IPPROTO_TCP,
                    "udp": _socket.IPPROTO_UDP,
        }

        #supported only by IP
        if is_cli:
            proto_map.update(
                {"dstopts": _socket.IPPROTO_DSTOPTS,
                "none": _socket.IPPROTO_NONE,
                "raw": _socket.IPPROTO_RAW,
                "ipv4": _socket.IPPROTO_IPV4,
                "ipv6": _socket.IPPROTO_IPV6,
                "esp": _socket.IPPROTO_ESP,
                "fragment": _socket.IPPROTO_FRAGMENT,
                "nd": _socket.IPPROTO_ND,
                "icmpv6": _socket.IPPROTO_ICMPV6,
                "routing": _socket.IPPROTO_ROUTING,
                "pup": _socket.IPPROTO_PUP, #http://ironpython.codeplex.com/WorkItem/View.aspx?WorkItemId=21918
                "ggp": _socket.IPPROTO_GGP, #http://ironpython.codeplex.com/WorkItem/View.aspx?WorkItemId=21918
                })

        for proto_name, good_val in proto_map.items():
            temp_val = _socket.getprotobyname(proto_name)
            self.assertEqual(temp_val, good_val)

        #negative cases
        bad_list = ["", "blah", "i"]
        for name in bad_list:
            self.assertRaises(_socket.error, _socket.getprotobyname, name) 
Example 55
Project: snmpsim   Author: etingof   File: endpoints.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def parse_endpoint(arg, ipv6=False):
    address = arg

    # IPv6 notation
    if ipv6 and address.startswith('['):
        address = address.replace('[', '').replace(']', '')

    try:
        if ':' in address:
            address, port = address.split(':', 1)
            port = int(port)

        else:
            port = 161

    except Exception as exc:
        raise SnmpsimError(
            'Malformed network endpoint address %s: %s' % (arg, exc))

    try:
        address, port = socket.getaddrinfo(
            address, port,
            socket.AF_INET6 if ipv6 else socket.AF_INET,
            socket.SOCK_DGRAM,
            socket.IPPROTO_UDP)[0][4][:2]

    except socket.gaierror as exc:
        raise SnmpsimError(
            'Unknown hostname %s: %s' % (address, exc))

    return address, port 
Example 56
Project: scalyr-agent-2   Author: scalyr   File: transport.py    License: Apache License 2.0 5 votes vote down vote up
def _resolveAddr(self, transportAddr):
        try:
            return socket.getaddrinfo(transportAddr[0],
                                      transportAddr[1],
                                      socket.AF_INET,
                                      socket.SOCK_DGRAM,
                                      socket.IPPROTO_UDP)[0][4][:2]
        except socket.gaierror:
            raise error.PySnmpError('Bad IPv4/UDP transport address %s: %s' % ('@'.join([ str(x) for x in transportAddr ]), sys.exc_info()[1])) 
Example 57
Project: scalyr-agent-2   Author: scalyr   File: transport.py    License: Apache License 2.0 5 votes vote down vote up
def _resolveAddr(self, transportAddr):
        try:
            return socket.getaddrinfo(transportAddr[0],
                                      transportAddr[1],
                                      socket.AF_INET6,
                                      socket.SOCK_DGRAM,
                                      socket.IPPROTO_UDP)[0][4][:2]
        except socket.gaierror:
            raise error.PySnmpError('Bad IPv6/UDP transport address %s: %s' % ('@'.join([ str(x) for x in transportAddr ]), sys.exc_info()[1])) 
Example 58
Project: scalyr-agent-2   Author: scalyr   File: transport.py    License: Apache License 2.0 5 votes vote down vote up
def _resolveAddr(self, transportAddr):
        try:
            return socket.getaddrinfo(transportAddr[0],
                                      transportAddr[1],
                                      socket.AF_INET,
                                      socket.SOCK_DGRAM,
                                      socket.IPPROTO_UDP)[0][4][:2]
        except socket.gaierror:
            raise error.PySnmpError('Bad IPv4/UDP transport address %s: %s' % ('@'.join([ str(x) for x in transportAddr ]), sys.exc_info()[1])) 
Example 59
Project: scalyr-agent-2   Author: scalyr   File: transport.py    License: Apache License 2.0 5 votes vote down vote up
def _resolveAddr(self, transportAddr):
        try:
            return socket.getaddrinfo(transportAddr[0],
                                      transportAddr[1],
                                      socket.AF_INET6,
                                      socket.SOCK_DGRAM,
                                      socket.IPPROTO_UDP)[0][4][:2]
        except socket.gaierror:
            raise error.PySnmpError('Bad IPv6/UDP transport address %s: %s' % ('@'.join([ str(x) for x in transportAddr ]), sys.exc_info()[1])) 
Example 60
Project: scalyr-agent-2   Author: scalyr   File: transport.py    License: Apache License 2.0 5 votes vote down vote up
def _resolveAddr(self, transportAddr):
        try:
            return socket.getaddrinfo(transportAddr[0],
                                      transportAddr[1],
                                      socket.AF_INET,
                                      socket.SOCK_DGRAM,
                                      socket.IPPROTO_UDP)[0][4][:2]
        except socket.gaierror:
            raise error.PySnmpError('Bad IPv4/UDP transport address %s: %s' % ('@'.join([ str(x) for x in transportAddr ]), sys.exc_info()[1]))