我为我的 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 多播地址接收数据。我将非常感谢任何想法,并对我的英语感到抱歉。 ;-)
此示例在 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))
更完整的答案 https://stackoverflow.com/a/66943594/8625835
我是一名优秀的程序员,十分优秀!