在所有网络接口上发送m-search数据包

时间:2014-06-12 07:17:27

标签: python-2.7 twisted assertion reactor ssdp

我正在实现一个代码,通过该代码我必须将设备连接到我机器上的所有网络接口。

为此,我首先获取所有网络接口的ip,然后发送m-search命令。

2.5秒后,端口停止侦听。

但它给了我一些断言错误。

Code:

class Base(DatagramProtocol):
    """ Class to send M-SEARCH message to devices in network and receive datagram
        packets from them
    """
    SSDP_ADDR = "239.255.255.250"
    SSDP_PORT = 1900
    MS = "M-SEARCH * HTTP/1.1\r\nHOST: {}:{}\r\nMAN: 'ssdp:discover'\r\nMX: 2\r\nST: ssdp:all\r\n\r\n".format(SSDP_ADDR, SSDP_PORT)

def sendMsearch(self):
    """ Sending M-SEARCH message
    """
    ports = []
    for address in self.addresses:
        ports.append(reactor.listenUDP(0, self, interface=address))

    for port in ports:
        for num in range(4):
            port.write(Base.MS, (Base.SSDP_ADDR,Base.SSDP_PORT))
        reactor.callLater(2.5, self.stopMsearch, port) # MX + a wait margin


def stopMsearch(self, port):
    """ Stop listening on port
    """
    port.stopListening()

Error:

Traceback (most recent call last):
  File "work\find_devices.py", line 56, in sendMsearch
    ports.append(reactor.listenUDP(0, self, interface=address))
  File "C:\Python27\lib\site-packages\twisted\internet\posixbase.py", line 374, in listenUDP
    p.startListening()
  File "C:\Python27\lib\site-packages\twisted\internet\udp.py", line 172, in startListening
    self._connectToProtocol()
  File "C:\Python27\lib\site-packages\twisted\internet\udp.py", line 210, in _connectToProtocol
    self.protocol.makeConnection(self)
  File "C:\Python27\lib\site-packages\twisted\internet\protocol.py", line 709, in makeConnection
    assert self.transport == None
AssertionError

请告诉我们此代码中的错误以及如何解决此问题。

同样在linux机器上,如果在网络上找不到设备,那么它不会去stopMsearch()为什么?

1 个答案:

答案 0 :(得分:2)

协议只能有一个传输。循环:

for address in self.addresses:
    ports.append(reactor.listenUDP(0, self, interface=address))

尝试创建多个UDP传输并将它们全部与self - 一个协议实例相关联。

这就是断言错误告诉你的。协议的传输必须是None(即,它必须没有传输)。但是在循环的第二次迭代中,它已经有了传输。

尝试使用多个协议实例。