从Python Socket Recv获取多播目标 [英] Get Multicast Dest from Python Socket Recv

查看:129
本文介绍了从Python Socket Recv获取多播目标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

For my project, I need some way to know which multicast group a packet was originally sent to when it's received by my client. I've considered maintaining a map of sockets to multicast groups and identifying them this way, but surely there's some way to get the address from the datagram?

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

To listen, I'm currently using:

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

这可以工作,但是接收时的地址是发送方机器的地址.如何查看发送到的组播组?

Which works, but the address when received is that of the sending machine. How can I see the multicast group it was sent to?

谢谢!

推荐答案

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

You only joined multicast group address "ff02::abcd:1". Therefore, any packet that is received on the socket must have been sent to that multicast address.

这篇关于从Python Socket Recv获取多播目标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆