Python socket.IPPROTO_IP() Examples

The following are code examples for showing how to use socket.IPPROTO_IP(). 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: NiujiaoDebugger   Author: MrSrc   File: mcast.py    GNU General Public License v3.0 7 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
Project: AshsSDK   Author: thehappydinoa   File: client.py    MIT License 6 votes vote down vote up
def _socketpair_compat():
    """TCP/IP socketpair including Windows support"""
    listensock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP)
    listensock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    listensock.bind(("127.0.0.1", 0))
    listensock.listen(1)

    iface, port = listensock.getsockname()
    sock1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP)
    sock1.setblocking(0)
    try:
        sock1.connect(("127.0.0.1", port))
    except socket.error as err:
        if err.errno != errno.EINPROGRESS and err.errno != errno.EWOULDBLOCK and err.errno != EAGAIN:
            raise
    sock2, address = listensock.accept()
    sock2.setblocking(0)
    listensock.close()
    return (sock1, sock2) 
Example 3
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 4
Project: benchexec   Author: sosy-lab   File: container.py    Apache License 2.0 6 votes vote down vote up
def activate_network_interface(iface):
    """Bring up the given network interface.
    @raise OSError: if interface does not exist or permissions are missing
    """
    iface = iface.encode()

    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_IP)
    try:
        # Get current interface flags from kernel
        ifreq = struct.pack(
            _STRUCT_IFREQ_LAYOUT_IFADDR_SAFAMILY, iface, socket.AF_INET, b"0" * 14
        )
        ifreq = fcntl.ioctl(sock, _SIOCGIFFLAGS, ifreq)
        if_flags = struct.unpack(_STRUCT_IFREQ_LAYOUT_IFFLAGS, ifreq)[1]

        # Set new flags
        ifreq = struct.pack(
            _STRUCT_IFREQ_LAYOUT_IFFLAGS, iface, if_flags | _IFF_UP, b"0" * 14
        )
        fcntl.ioctl(sock, _SIOCSIFFLAGS, ifreq)
    finally:
        sock.close() 
Example 5
Project: dockerizeme   Author: dockerizeme   File: snippet.py    Apache License 2.0 6 votes vote down vote up
def client(timeout=1, retries=5):
    socket.setdefaulttimeout(timeout)

    for _ in xrange(retries):
        for addr in interface_addresses():
            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((addr, 0))

            msg = DISCOVERY_MSG % dict(service='id1', library=LIB_ID)
            for _ in xrange(2):
                # sending it more than once will
                # decrease the probability of a timeout
                sock.sendto(msg, (MCAST_GRP, MCAST_PORT))

            try:
                data = sock.recv(1024)
            except socket.timeout:
                pass
            else:
                response = Response(data)
                print response.getheader('Location')
                return 
Example 6
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 7
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 8
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 9
Project: icmp-remote-shell   Author: alex-kostirin   File: common.py    MIT License 6 votes vote down vote up
def start_sniffing(host, log_file):
    s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
    s.bind((host, 0))
    s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)
    print("Sniffer Started.....")
    while True:
        try:
            data = s.recvfrom(65565)
            d1 = data[0]
            if bytearray(d1)[20] != ICMP_ECHO_REQUEST_TYPE:
                continue
            d1 = str(d1)
            data1 = re.search('@@(.*)\'', d1)
            data_part = data1.group(0)
            data_part = data_part[:len(data_part) - 1]
            writer(data_part, log_file)
            print("Command output:", reader(log_file))
        except:
            pass 
Example 10
Project: DIALScan   Author: bahorn   File: ssdp.py    MIT License 6 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)
        sock.sendto(bytes(message.format(*group, st=service, mx=mx), 'ascii'), group)
        while True:
            try:
                response = SSDPResponse(sock.recv(1024))
                responses[response.location] = response
            except socket.timeout:
                break
    return responses.values() 
Example 11
Project: dbus-mqtt   Author: liaan   File: client.py    MIT License 6 votes vote down vote up
def _socketpair_compat():
    """TCP/IP socketpair including Windows support"""
    listensock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP)
    listensock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    listensock.bind(("127.0.0.1", 0))
    listensock.listen(1)

    iface, port = listensock.getsockname()
    sock1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP)
    sock1.setblocking(0)
    try:
        sock1.connect(("localhost", port))
    except socket.error as err:
        if err.errno != errno.EINPROGRESS and err.errno != errno.EWOULDBLOCK and err.errno != EAGAIN:
            raise
    sock2, address = listensock.accept()
    sock2.setblocking(0)
    listensock.close()
    return (sock1, sock2) 
Example 12
Project: hyperion.control   Author: hyperion-project   File: ssdp.py    MIT License 6 votes vote down vote up
def discover(service, timeout=3, retries=1, mx=2):
    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)
        sock.sendto(message.format(*group, st=service, mx=mx), group)
        while True:
            try:
                response = SSDPResponse(sock.recv(1024))
                responses[response.location] = response
            except socket.timeout:
                break
    return responses.values() 
Example 13
Project: virtual-hue   Author: flok99   File: htx.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def _startSSDPNotifier(addr):
    msgHeader = [
            'NOTIFY * HTTP/1.1\r\n',
            'HOST: 239.255.255.250:1900\r\n',
            "NTS: ssdp:alive\r\n"
        ]

    msg = ''.join(msgHeader) + gen_ssdp_content(addr, 'NT')

    while True:
        print "Sending M-NOTIFY..."
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 32)
        sock.sendto(msg, (ssdp_addr, ssdp_port))
        sock.close()
        del sock

        time.sleep(6) 
Example 14
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 15
Project: Paradrop   Author: ParadropLabs   File: discover.py    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 16
Project: piescan   Author: m57   File: piescan.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def sniffer_thread(target):

    sniffer = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
    sniffer.bind(("0.0.0.0", 0 ))
    sniffer.settimeout(5)
    sniffer.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)

    # continually read in packets and parse their information
    while ( 1 ):
	try:
	        raw_buffer = sniffer.recvfrom(65565)[0]
        
	except:
		if (SNIFF_MUTEX == 0):
			sys.exit(1)

	ip_header = raw_buffer[0:20]
	dst_port = struct.unpack(">h", raw_buffer[0x32:0x34])[0]
        iph = struct.unpack('!BBHHHBBH4s4s' , ip_header)

        # Create our IP structure
        version_ihl = iph[0]
        ihl = version_ihl & 0xF
        iph_length = ihl * 4
        src_addr = socket.inet_ntoa(iph[8]);

        # Create our ICMP structure
        buf = raw_buffer[iph_length:iph_length + ctypes.sizeof(ICMP)]
        icmp_header = ICMP(buf)

        # check for the type 3 and code and within our target subnet
        if icmp_header.code == 3 and icmp_header.type == 3 and src_addr == target:
		if dst_port not in ports_ident["closed"]:
			ports_ident["closed"].append(dst_port) 
Example 17
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 18
Project: rift-python   Author: brunorijsman   File: interface.py    Apache License 2.0 5 votes vote down vote up
def ties_ack_table(self):
        return self.tie_headers_lifetime_table_cmn(self._ties_ack)

    # TODO: Set TTL as follows:
    # 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)

    # TODO: Set TOS and Priority 
Example 19
Project: rift-python   Author: brunorijsman   File: interface.py    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 20
Project: igd-exporter   Author: yrro   File: wsgiext.py    MIT License 5 votes vote down vote up
def server_bind(self):
        self.socket.setsockopt(socket.IPPROTO_IP, 15, 1) # IP_FREEBIND
        if self.__bind_v6only is not None and self.address_family == socket.AF_INET6:
            self.socket.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, self.__bind_v6only)
        super().server_bind() 
Example 21
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 22
Project: samsung_remote   Author: pedrinho   File: ssdp.py    The Unlicense 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 23
Project: genmon   Author: jgyates   File: genalexa.py    GNU General Public License v2.0 5 votes vote down vote up
def init_socket(self):
        ok = True
        self.ip = '239.255.255.250'
        self.port = 1900
        try:
            #This is needed to join a multicast group
            self.mreq = struct.pack("4sl",socket.inet_aton(self.ip),socket.INADDR_ANY)

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

            try:
                self.ssock.bind(('',self.port))
            except Exception as e:
                self.LogError("WARNING: Failed to bind %s:%d: %s" , (self.ip,self.port,e))
                ok = False

            try:
                self.ssock.setsockopt(socket.IPPROTO_IP,socket.IP_ADD_MEMBERSHIP,self.mreq)
            except Exception as e:
                self.LogError('WARNING: Failed to join multicast group:'+str(e))
                ok = False

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

    # ---------------- upnp_broadcast_responder.fileno ------------------------- 
Example 24
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 25
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 26
Project: goodbye-mihome   Author: aluminiumgeek   File: yeelight.py    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 27
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 28
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 29
Project: ros2cli   Author: ros2   File: __init__.py    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 30
Project: HomeAssistant_Components   Author: charleyzhu   File: dlna.py    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 31
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 32
Project: diamond-next   Author: diamond-next   File: gmetric.py    MIT License 5 votes vote down vote up
def __init__(self, host, port, protocol):
        if protocol not in self.protocol:
            raise ValueError("Protocol must be one of: " + str(self.protocol))

        self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        if protocol == 'multicast':
            self.socket.setsockopt(socket.IPPROTO_IP,
                                   socket.IP_MULTICAST_TTL, 20)
        self.hostport = (host, int(port))
        # self.socket.connect(self.hostport) 
Example 33
Project: open-recipe   Author: dspray95   File: udp.py    The Unlicense 5 votes vote down vote up
def getOutgoingInterface(self):
        i = self.socket.getsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_IF)
        return socket.inet_ntoa(struct.pack("@i", i)) 
Example 34
Project: open-recipe   Author: dspray95   File: udp.py    The Unlicense 5 votes vote down vote up
def _setInterface(self, addr):
        i = socket.inet_aton(addr)
        self.socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_IF, i)
        return 1 
Example 35
Project: open-recipe   Author: dspray95   File: udp.py    The Unlicense 5 votes vote down vote up
def getLoopbackMode(self):
        return self.socket.getsockopt(socket.IPPROTO_IP,
                                      socket.IP_MULTICAST_LOOP) 
Example 36
Project: open-recipe   Author: dspray95   File: udp.py    The Unlicense 5 votes vote down vote up
def setLoopbackMode(self, mode):
        mode = struct.pack("b", operator.truth(mode))
        self.socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP,
                               mode) 
Example 37
Project: open-recipe   Author: dspray95   File: udp.py    The Unlicense 5 votes vote down vote up
def getTTL(self):
        return self.socket.getsockopt(socket.IPPROTO_IP,
                                      socket.IP_MULTICAST_TTL) 
Example 38
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 39
Project: open-recipe   Author: dspray95   File: udp.py    The Unlicense 5 votes vote down vote up
def getOutgoingInterface(self):
        i = self.socket.getsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_IF)
        return socket.inet_ntoa(struct.pack("@i", i)) 
Example 40
Project: open-recipe   Author: dspray95   File: udp.py    The Unlicense 5 votes vote down vote up
def _setInterface(self, addr):
        i = socket.inet_aton(addr)
        self.socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_IF, i)
        return 1 
Example 41
Project: open-recipe   Author: dspray95   File: udp.py    The Unlicense 5 votes vote down vote up
def getLoopbackMode(self):
        return self.socket.getsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP) 
Example 42
Project: open-recipe   Author: dspray95   File: udp.py    The Unlicense 5 votes vote down vote up
def setLoopbackMode(self, mode):
        mode = struct.pack("b", operator.truth(mode))
        self.socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, mode) 
Example 43
Project: open-recipe   Author: dspray95   File: udp.py    The Unlicense 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 44
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 45
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 46
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 47
Project: icmp-remote-shell   Author: alex-kostirin   File: server.py    MIT License 5 votes vote down vote up
def main():
    args = parse_args()
    host = args.host
    ping_delay = args.ping_delay
    s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
    s.bind((host, 0))
    s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)
    #  s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON)
    print("Server Started......")
    while True:
        # while 1:
        data = s.recvfrom(65565)
        d1 = data[0]
        if bytearray(d1)[20] != ICMP_ECHO_REQUEST_TYPE:
            continue
        d1 = str(d1)
        data1 = re.search('@@(.*)', d1)
        command = data1.group(0)
        cmd = command[2:len(command) - 1]
        d = data[1]
        d1 = str(d)
        ip = d1[2:-5]
        # print ip
        print(cmd)  # Holding the command to execute
        print(ip)  # Holding the destination address to send the ping
        output = execute(cmd)
        for line in output.readlines():
            send_one(ip, ping_delay, line) 
Example 48
Project: tello-udp   Author: alecGraves   File: tello.py    The Unlicense 5 votes vote down vote up
def __init__(self, interface=2, timeout=2):
        self.sock = socket.socket(socket.AF_INET, # Internet
               socket.SOCK_DGRAM, socket.IPPROTO_UDP) # UDP
        # self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, interface)
        
        # set timeout in seconds
        self.sock.settimeout(timeout) 
Example 49
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 50
Project: rpi3-webiopi   Author: thortex   File: coap.py    Apache License 2.0 5 votes vote down vote up
def __init__(self):
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.socket.settimeout(3.0)
        self.socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.socket.bind(('', 0))