从Python Socket Recv获取多播目标

时间:2018-11-26 19:38:39

标签: python python-3.x sockets udp multicast

对于我的项目,我需要某种方式来知道客户端接收到数据包时最初将其发送到哪个多播组。我已经考虑过维护一个套接字到多播组的映射并以此方式标识它们,但是肯定有某种方法可以从数据报中获取地址?

要收听,我当前正在使用:

# Initialise socket for IPv6 datagrams
sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM, socket.IPPROTO_UDP)

# Allows address to be reused
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

# Binds to all interfaces on the given port
sock.bind(('', 8080))

# Allow messages from this socket to loop back for development
sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_LOOP, True)

# Construct message for joining multicast group
mreq = struct.pack("16s15s".encode('utf-8'), socket.inet_pton(socket.AF_INET6, "ff02::abcd:1"), (chr(0) * 16).encode('utf-8'))
sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_JOIN_GROUP, mreq)

data, addr = sock.recvfrom(1024)

并发送:

# Create ipv6 datagram socket
sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
# Allow own messages to be sent back (for local testing)
sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_LOOP, True)
sock.sendto("hello world".encode('utf-8'), ("ff02::abcd:1", 8080))

可以使用,但是接收时的地址是发送方机器的地址。如何查看发送到的组播组?

谢谢!

1 个答案:

答案 0 :(得分:0)

您仅加入了多播组地址“ ff02 :: abcd:1”。因此,套接字上接收到的所有数据包都必须已发送到该多播地址。