RAW socket UDP Multicast in IPv6

丶灬走出姿态 提交于 2019-12-12 18:06:00

问题


i receive data from multicast for my UDP sniffer, but only in IPv4. My code looks like this,

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)

But i am receiving data only when i set IPv4 address, and i want also receive from IPv6 multicast address. I will be really grateful for any ideas and sorry for my english. ;-)


回答1:


this example gets a multicast on FF02::158 (IoTivity UDP CoAP) in Windows

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))



回答2:


You need to use the sockopt IPV6_ADD_MEMBERSHIP, as the API between IPv6 and IPv4 is slightly different. This is a good example.




回答3:


This is what I'm doing in 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))

This is for a DHCPv6 server, but you'll get the idea.

If you also want to get multicast packets transmitted by yourself you have to add:

mc_sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_LOOP, 1)


来源:https://stackoverflow.com/questions/40468331/raw-socket-udp-multicast-in-ipv6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!