【问题标题】:How to get Multicast Group Address from datagramReceived in Twisted?如何从 Twisted 中的 datagramReceived 中获取多播组地址?
【发布时间】:2012-07-09 18:00:09
【问题描述】:

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

问题:如何在 Twisted 协议/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()

【问题讨论】:

    标签: python udp twisted multicast


    【解决方案1】:

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

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

    【讨论】:

    • 这样做会调用多个线程吗?我正在将数据报写入一个在任何级别都没有锁定的数据结构。
    • 不,只需在 reactor.run() 之前多次调用listenUDP(或从反应堆事件调度的某些函数) - 不需要线程。
    猜你喜欢
    • 1970-01-01
    • 2012-01-12
    • 2015-01-08
    • 1970-01-01
    • 2021-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多