我从UDP嗅探器的多播接收数据,但仅在IPv4中。 我的代码看起来像这样,
try:
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_UDP)
except socket.error as msg:
print('Socket could not be created. Error Code : ' + str(msg[0]) + ' Message ' + msg[1])
sys.exit()
mreq = struct.pack("4sl", socket.inet_aton('239.255.11.3'), socket.INADDR_ANY)
# receive a packet
s.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
packet = s.recvfrom(65000)
但是我只在设置IPv4地址时才接收数据,并且我也希望从IPv6多播地址接收数据。 我会非常感激任何想法并抱歉我的英语。 ;-)
答案 0 :(得分:2)
此示例在Windows中的FF02 :: 158(IoTivity UDP CoAP)上获得多播
import socket
import struct
address = ('', 5683)
interface_index = 0 # default
sock = socket.socket(family=socket.AF_INET6, type=socket.SOCK_DGRAM)
sock.bind(address)
for group in ['ff02::158']: # multiple addresses can be specified
sock.setsockopt(
41, # socket.IPPROTO_IPV6 = 41 - not found in windows 10, bug python
socket.IPV6_JOIN_GROUP,
struct.pack(
'16si',
socket.inet_pton(socket.AF_INET6, group),
interface_index
)
)
while True:
data, sender = sock.recvfrom(1500)
while data[-1:] == '\0': data = data[:-1]
print(str(sender) + ' ' + repr(data))
答案 1 :(得分:0)
您需要使用sockopt IPV6_ADD_MEMBERSHIP,因为IPv6和IPv4之间的API略有不同。 This就是一个很好的例子。
答案 2 :(得分:0)
这就是我在my code中所做的事情:
mc_address = ipaddress.IPv6Address('ff02::1:2')
listen_port = 547
interface_index = socket.if_nametoindex('eth0')
mc_sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
mc_sock.bind((str(mc_address), listen_port, 0, interface_index))
mc_sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_JOIN_GROUP,
struct.pack('16sI', mc_address.packed, interface_index))
这适用于DHCPv6服务器,但您可以理解。
如果您还希望获得自己传输的组播数据包,则必须添加:
mc_sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_LOOP, 1)