gpt4 book ai didi

python - IPv6 中的 RAW 套接字 UDP 多播

转载 作者:太空宇宙 更新时间:2023-11-04 03:02:42 25 4
gpt4 key购买 nike

我为我的 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

关于python - IPv6 中的 RAW 套接字 UDP 多播,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40468331/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com