python - 如何从 Twisted 中的 datagramReceived 中获取多播组地址?

标签 python udp twisted multicast

这是来自 Twisted 的以下代码示例,用于处理多播接收。我目前正在用同一个客户端收听许多组,我希望能够打印出某个数据报包来自哪个组。我认为这可以从 datagramReceived 的地址参数中接收;然而,这只给我一个元组,其中包含一个组绑定(bind)到的本地 ip 和端口,而不是组本身的地址。

问题:如何在 Twisted 协议(protocol)/API 中打印数据报来源的多播地址?

from twisted.internet.protocol import DatagramProtocol
from twisted.internet import reactor


class MulticastPingClient(DatagramProtocol):

    def startProtocol(self):
        # Join the multicast address, so we can receive replies:
        self.transport.joinGroup("228.0.0.5")
        self.transport.joinGroup("229.0.2.11")
        self.transport.joinGroup("221.3.3.3")
        # Send to 228.0.0.5:8005 - all listeners on the multicast address
        # (including us) will receive this message.
        self.transport.write('Client: Ping', ("228.0.0.5", 8005))

    def datagramReceived(self, datagram, address):
        print "Datagram %s received from %s" % (repr(datagram), repr(address))


reactor.listenMulticast(8005, MulticastPingClient(), listenMultiple=True)
reactor.run()

最佳答案

不幸的是,套接字 APIs Twisted wraps(通过 Python 的标准库)不提供此信息。我建议为每个多播组使用一个单独的 DatagramProtocol,并为每个组监听不同的端口。尽管有人仍然可以将 UDP 数据报直接发送到该端口,但您无法将其与多播区分开来。

我有一个模糊的内存表明 recvmsg() API 确实提供了必要的信息,尽管我没有时间验证这一点。 Twisted 12.1 开始有一个 recvmsg() 包装器,因此这可能是一种将此功能添加到 Twisted(或您的代码)的可能方法,但需要做更多的工作。

关于python - 如何从 Twisted 中的 datagramReceived 中获取多播组地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11400494/

相关文章:

ios - codenameone 多播 udp 的 IOS 权利

python - 当我运行不带任何选项的 `twistd` 命令时,为什么我的扭曲插件没有出现?

python - 具有适当符号的 Numpy 八函数

python - sklearn 的 pairwise_distances 和 metric ='correlation' 有什么作用?

python - Pandas 数据框的形状到 3d 数组

c++ - 无法分配请求的地址,C++ UDP 套接字

python - 从 None 获取 "raise JSONDecodeError("Expecting value", s, err.value) json.decoder.JSONDecodeError

c - pthread_mutex_lock 需要很多时间

python - 在linux上运行autobahn python会出现异常。AttributeError : Router instance has no attribute 'broker'

python - 如何在我的 Python 程序中找到内存泄漏?