无需提前指定INET或者INET6。
MYGROUP_4 = '225.0.0.250'
MYGROUP_6 = 'ff15:7079:7468:6f6e:6465:6d6f:6d63:6173'
addrinfo = socket.getaddrinfo(MYGROUP_6, None)[0]
(10, 1, 6, '', ('ff02::1:3', 0, 0, 0))
返回第一个参数是socket.AF_INET6
获取第一个参数就可以知道ipv4/ipv6
ttl_bin = struct.pack('@i', MYTTL: int)
s.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl_bin)
s.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_HOPS, ttl_bin)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
接收所有多播组:s.bind(('', MYPORT))
接收指定多播组:s.bind(('224.0.0.252', MYPORT))
group_bin = socket.inet_pton(addrinfo[0], addrinfo[4][0])
ipv4:
mreq = group_bin + struct.pack('=I', socket.INADDR_ANY)
s.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
ipv6:
后面的加的是接口索引,0表示默认网络接口
mreq = group_bin + struct.pack('@I', 0)
s.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_JOIN_GROUP, mreq)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_IF, socket.inet_aton(addr))
host = socket.gethostbyname(socket.gethostname())
sock.setsockopt(socket.SOL_IP, socket.IP_MULTICAST_IF, socket.inet_aton(host))
group_ipv6 = "FF02::1:3"
llmnr_port = 5355
s_ipv6 = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
s_ipv6.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s_ipv6.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_HOPS, struct.pack('@i', 255))
group = socket.inet_pton(socket.AF_INET6, group_ipv6)
if system() == "Windows":
mreq = group + struct.pack('@I', get_ipv6_ifindex(get_iface_by_ip(targer_ip)))
else:
mreq = group + struct.pack('@I', socket.if_nametoindex(get_iface_by_ip(targer_ip)))
s_ipv6.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_JOIN_GROUP, mreq)
s_ipv6.bind((group_ipv6, llmnr_port))
iface
是网卡对象,比如
,获取网卡索引两种方式:
int(netifaces.ifaddresses(iface.guid)[socket.AF_INET6][-1]["broadcast"].split("%")[-1])
iface.win_index
targer_ip
是要监听网段上的任意地址system()
是from platfrom import system
windows ipv6绑定接口参考链接:
https://stackoverflow.com/questions/47280816/windows-doesnt-receive-multicast-ipv6-packets-from-all-interfaces
https://docs.python.org/3/library/socket.html