Python socket.IP_ADD_MEMBERSHIP Examples
The following are 30
code examples of socket.IP_ADD_MEMBERSHIP().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
socket
, or try the search function
.
Example #1
Source File: multicast_checks.py From rift-python with Apache License 2.0 | 7 votes |
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
Source File: gateway.py From PyXiaomiGateway with MIT License | 7 votes |
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 #3
Source File: coap.py From pyShelly with MIT License | 6 votes |
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 #4
Source File: udp_listener.py From mmvt with GNU General Public License v3.0 | 6 votes |
def bind_to_multicast(port=45454, multicast_group='239.255.43.21'): import struct # Create the socket sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # Bind to the server address # sock.bind((multicast_group, port)) sock.bind(('', port)) # Tell the operating system to add the socket to the multicast group # on all interfaces. # group = socket.inet_aton(multicast_group) # mreq = struct.pack('4sL', group, socket.INADDR_ANY) mreq = struct.pack('4sl', socket.inet_aton(multicast_group), socket.INADDR_ANY) sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq) return sock
Example #5
Source File: discover.py From fluxclient with GNU Affero General Public License v3.0 | 6 votes |
def create_sockets(mcst_ipaddr, mcst_port): mreq = struct.pack("4sl", socket.inet_aton(mcst_ipaddr), socket.INADDR_ANY) s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq) if platform.system() == "Windows": s.bind(("", mcst_port)) return (s, ) else: s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) s.bind((mcst_ipaddr, mcst_port)) bsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) bsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) bsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) bsock.bind(("", 1901)) return (s, bsock)
Example #6
Source File: wsdd.py From wsdd with MIT License | 6 votes |
def init_v4(self): idx = socket.if_nametoindex(self.interface.name) self.multicast_address = (WSD_MCAST_GRP_V4, WSD_UDP_PORT) # v4: member_request (ip_mreqn) = { multicast_addr, intf_addr, idx } mreq = ( socket.inet_pton(self.family, WSD_MCAST_GRP_V4) + socket.inet_pton(self.family, self.address) + struct.pack('@I', idx)) self.recv_socket.setsockopt( socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq) try: self.recv_socket.bind((WSD_MCAST_GRP_V4, WSD_UDP_PORT)) except OSError: self.recv_socket.bind(('', WSD_UDP_PORT)) self.send_socket.setsockopt( socket.IPPROTO_IP, socket.IP_MULTICAST_IF, mreq) self.send_socket.setsockopt( socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 0) self.send_socket.setsockopt( socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, args.hoplimit) self.listen_address = (self.address, WSD_HTTP_PORT)
Example #7
Source File: poc.py From pub with GNU General Public License v2.0 | 6 votes |
def __init__(self, group="239.255.255.250", port=1900): self.group, self.port = group, port self.callbacks = {} # multicast socket sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) logger.debug("[SSDP] bind: 0.0.0.0:%s" % port) sock.bind(('0.0.0.0', port)) mreq = struct.pack("=4sl", socket.inet_aton(group), socket.INADDR_ANY) logger.debug("[SSDP] add membership: UDP/%s" % group) sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq) self.listening = False self.sock = sock self.devices = {} # Start listening
Example #8
Source File: multicast-relay.py From multicast-relay with GNU General Public License v3.0 | 6 votes |
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 #9
Source File: __init__.py From PyXiaomiGateway with MIT License | 6 votes |
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 #10
Source File: utils.py From iptvtools with MIT License | 6 votes |
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 #11
Source File: listener.py From pulseaudio-dlna with GNU General Public License v3.0 | 6 votes |
def run(self, ttl=None): if self.DISABLE_SSDP_LISTENER: return self.allow_reuse_address = True SocketServer.UDPServer.__init__( self, (self.host or '', self.SSDP_PORT), SSDPHandler) self.socket.setsockopt( socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, self._multicast_struct(self.SSDP_ADDRESS)) self.socket.setsockopt( socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, self.SSDP_TTL) if ttl: GObject.timeout_add(ttl * 1000, self.shutdown) setproctitle.setproctitle('ssdp_listener') self.serve_forever(self) logger.info('SSDPListener.run()')
Example #12
Source File: __init__.py From ros2cli with Apache License 2.0 | 6 votes |
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 #13
Source File: hello.py From ros2cli with Apache License 2.0 | 6 votes |
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 #14
Source File: natnet.py From natnetclient with GNU General Public License v2.0 | 5 votes |
def __init__(self, client_ip=CLIENT_ADDRESS, port=PORT_DATA, max_packet_size=MAX_PACKETSIZE): """Internet Protocol socket with presets for Motive Data Socket.""" super(NatDataSocket, self).__init__(client_ip, port, max_packet_size) # Configure and Connect socket self._sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) mreq = socket.inet_aton(MULTICAST_ADDRESS) + socket.inet_aton(client_ip) self._sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq) self._sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, OPT_VAL) self._sock.bind((client_ip, port)) # self.bind((Optitrack.CLIENT_ADDRESS, socket.htons(Optitrack.PORT_DATA))) # If the above line doesn't work. self._sock.settimeout(60.0)
Example #15
Source File: ssdp.py From script.tubecast with MIT License | 5 votes |
def __init__(self, addr, handler, chromecast_addr, poll_interval=0.5, bind_and_activate=True, interfaces=None): ThreadingUDPServer.__init__(self, ('', addr[1]), handler, bind_and_activate) ControlMixin.__init__(self, handler, poll_interval) self.chromecast_addr = chromecast_addr self._multicast_address = addr self._listen_interfaces = interfaces self.set_loopback_mode(1) # localhost self.set_ttl(2) # localhost and local network self.handle_membership(socket.IP_ADD_MEMBERSHIP)
Example #16
Source File: ssdp.py From HRTunerProxy with GNU General Public License v2.0 | 5 votes |
def run(self): self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) if hasattr(socket, "SO_REUSEPORT"): try: self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) except socket.error as le: # RHEL6 defines SO_REUSEPORT but it doesn't work if le.errno == ENOPROTOOPT: pass else: raise addr = socket.inet_aton(SSDP_ADDR) interface = socket.inet_aton('0.0.0.0') cmd = socket.IP_ADD_MEMBERSHIP self.sock.setsockopt(socket.IPPROTO_IP, cmd, addr + interface) self.sock.bind(('0.0.0.0', SSDP_PORT)) self.sock.settimeout(1) while True: try: data, addr = self.sock.recvfrom(1024) self.datagram_received(data, addr) except socket.timeout: continue self.shutdown()
Example #17
Source File: udp.py From python-for-android with Apache License 2.0 | 5 votes |
def _joinAddr2(self, interface, addr, join): addr = socket.inet_aton(addr) interface = socket.inet_aton(interface) if join: cmd = socket.IP_ADD_MEMBERSHIP else: cmd = socket.IP_DROP_MEMBERSHIP try: self.socket.setsockopt(socket.IPPROTO_IP, cmd, addr + interface) except socket.error, e: return failure.Failure(error.MulticastJoinError(addr, interface, *e.args))
Example #18
Source File: udp.py From python-for-android with Apache License 2.0 | 5 votes |
def _joinAddr2(self, interface, addr, join): addr = socket.inet_aton(addr) interface = socket.inet_aton(interface) if join: cmd = socket.IP_ADD_MEMBERSHIP else: cmd = socket.IP_DROP_MEMBERSHIP try: self.socket.setsockopt(socket.IPPROTO_IP, cmd, addr + interface) except socket.error, e: return failure.Failure(error.MulticastJoinError(addr, interface, *e.args))
Example #19
Source File: tva.py From movistartv2xmltv with GNU General Public License v2.0 | 5 votes |
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 #20
Source File: udp.py From BitTorrent with GNU General Public License v3.0 | 5 votes |
def _joinAddr2(self, interface, addr, join): addr = socket.inet_aton(addr) interface = socket.inet_aton(interface) if join: cmd = socket.IP_ADD_MEMBERSHIP else: cmd = socket.IP_DROP_MEMBERSHIP try: self.socket.setsockopt(socket.IPPROTO_IP, cmd, addr + interface) except socket.error, e: return failure.Failure(error.MulticastJoinError(addr, interface, *e.args))
Example #21
Source File: tv_grab_es_movistartv.py From tv_grab_es_movistartv with GNU General Public License v3.0 | 5 votes |
def __get_xml_files(self, mc_grp, mc_port): try: loop = True chunk = {"end": 0} max_files = 1000 _files = {} first_file = '' logger.debug('Descargando XML de %s:%s' % (mc_grp, mc_port)) sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.settimeout(3) sock.bind((mc_grp, int(mc_port))) mreq = struct.pack("=4sl", socket.inet_aton(mc_grp), socket.INADDR_ANY) sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq) # Wait for an end chunk to start by the beginning while not (chunk["end"]): chunk = self.__parse_chunk(sock.recv(1500)) first_file = str(chunk["filetype"]) + "_" + str(chunk["fileid"]) # Loop until firstfile while loop: xmldata = "" chunk = self.__parse_chunk(sock.recv(1500)) # Discard headers body = chunk["data"] while not (chunk["end"]): xmldata += body chunk = self.__parse_chunk(sock.recv(1500)) body = chunk["data"] # Discard last 4bytes binary footer? xmldata += body[:-4] _files[str(chunk["filetype"]) + "_" + str(chunk["fileid"])] = xmldata logger.debug('XML: %s_%s' % (chunk["filetype"], chunk["fileid"])) max_files -= 1 if str(chunk["filetype"]) + "_" + str(chunk["fileid"]) == first_file or max_files == 0: loop = False sock.close() return _files except Exception, ex: logger.error('Error al descargar los archivos XML: %s' % str(ex.args))
Example #22
Source File: natnet.py From natnetclient with GNU General Public License v2.0 | 5 votes |
def __init__(self, client_ip=CLIENT_ADDRESS, port=PORT_DATA, max_packet_size=MAX_PACKETSIZE): """Internet Protocol socket with presets for Motive Data Socket.""" super(NatDataSocket, self).__init__(client_ip, port, max_packet_size) # Configure and Connect socket self._sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) mreq = socket.inet_aton(MULTICAST_ADDRESS) + socket.inet_aton(client_ip) self._sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq) self._sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, OPT_VAL) self._sock.bind((client_ip, port)) # self.bind((Optitrack.CLIENT_ADDRESS, socket.htons(Optitrack.PORT_DATA))) # If the above line doesn't work. self._sock.settimeout(60.0)
Example #23
Source File: mcast.py From odoo13-x64 with GNU General Public License v3.0 | 5 votes |
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 #24
Source File: registry.py From dubbo-python with Apache License 2.0 | 5 votes |
def __init__(self, address, callback): Thread.__init__(self) self.multicast_group, self.multicast_port = address.split(':') self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) # in osx we should use SO_REUSEPORT instead of SO_REUSEADDRESS self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) self.sock.bind(('', int(self.multicast_port))) mreq = struct.pack("4sl", socket.inet_aton(self.multicast_group), socket.INADDR_ANY) self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq) self.callback = callback
Example #25
Source File: udp_rx_handler.py From rift-python with Apache License 2.0 | 5 votes |
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 #26
Source File: dns.py From mitmcanary with GNU General Public License v3.0 | 5 votes |
def get_mdns_sock(self): sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) if sys.platform == 'darwin': sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) sock.bind(('', 5353)) mreq = struct.pack("4sl", socket.inet_aton('224.0.0.251'), socket.INADDR_ANY) sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq) return sock
Example #27
Source File: receiver.py From WaveSync with MIT License | 5 votes |
def connection_made(self, transport): "Configure multicast" sock = transport.get_extra_info('socket') sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # Check if address is multicast and join group. group, port = self.channel multicast = True octets = group.split('.') # Received audio chunk counter self.chunk_queue.init_queue() if len(octets) != 4: multicast = False else: try: octet_0 = int(octets[0]) if not 224 <= octet_0 <= 239: multicast = False except ValueError: multicast = False # If not multicast - end if multicast is False: print("Assuming unicast reception on %s:%d" % (group, port)) return # Multicast - join group print("Joining multicast group", group) group = socket.inet_aton(group) mreq = struct.pack('4sL', group, socket.INADDR_ANY) sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
Example #28
Source File: packetizer.py From WaveSync with MIT License | 5 votes |
def create_socket(self, channels, ttl, multicast_loop, broadcast, source_address=None): "Create a UDP multicast socket" self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl) for address, port in channels: if source_address and ipaddress.IPv4Address(address).is_multicast: try: self.sock.setsockopt(socket.SOL_IP, socket.IP_MULTICAST_IF, socket.inet_aton(source_address)) print("added membership, interface source address: %s, group: %s" % (source_address, address)) self.sock.setsockopt(socket.SOL_IP, socket.IP_ADD_MEMBERSHIP, socket.inet_aton(address) + socket.inet_aton(source_address)) except: print("failed to add membership, interface source address: %s, group: %s. This is ok for unicast." % (source_address, address)) if multicast_loop is True: self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 1) if broadcast is True: self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) self.destinations = [ (address, port) for address, port in channels ] IP_PMTUDISC_DO = 2 IP_MTU_DISCOVER = 10 # Set DF flag on IP packet (Don't Fragment) - fragmenting would be bad idea # it's way better to chunk the packets right. self.sock.setsockopt(socket.IPPROTO_IP, IP_MTU_DISCOVER, IP_PMTUDISC_DO)
Example #29
Source File: mcast.py From android_universal with MIT License | 5 votes |
def receiver(group): # Look up multicast group address in name server and find out IP version addrinfo = socket.getaddrinfo(group, None)[0] # Create a socket s = socket.socket(addrinfo[0], socket.SOCK_DGRAM) # Allow multiple copies of this program on one machine # (not strictly needed) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # Bind it to the port s.bind(('', MYPORT)) group_bin = socket.inet_pton(addrinfo[0], addrinfo[4][0]) # Join group if addrinfo[0] == socket.AF_INET: # IPv4 mreq = group_bin + struct.pack('=I', socket.INADDR_ANY) s.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq) else: mreq = group_bin + struct.pack('@I', 0) s.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_JOIN_GROUP, mreq) # Loop, printing any data we receive while True: data, sender = s.recvfrom(1500) while data[-1:] == '\0': data = data[:-1] # Strip trailing \0's print(str(sender) + ' ' + repr(data))
Example #30
Source File: udp_multicast.py From crazyswarm with MIT License | 5 votes |
def __init__(self, MCAST_GRP = '224.1.1.1', MCAST_PORT = 5007): self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.sock.bind(('', MCAST_PORT)) # use MCAST_GRP instead of '' to listen only # to MCAST_GRP, not all groups on MCAST_PORT mreq = struct.pack("4sl", socket.inet_aton(MCAST_GRP), socket.INADDR_ANY) self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)