[Twisted-Python] help with listening to UDP broadcast?

Russell E. Owen rowen at uw.edu
Fri Aug 8 16:58:26 MDT 2014


I've found an example for UDP broadcasting:
<https://twistedmatrix.com/trac/browser/trunk/docs/projects/core/examples
/udpbroadcast.py?rev=41516>

However, it combines the sender and receiver in a way that I find 
confusing. I figured out how output UDP broadcast packets, but not how 
to make a client that receives to the packets.

Here is what we have, which doesn't work. Based on a comment on the 
broadcast UDP ticket. I suspect the problem is specifying the broadcast 
address using the interface argument to listenUDP, but I'm not sure. In 
any case, no value for interface that I've tried works:
-"<broadcast>" (which is what my senders uses) results in 
twisted.internet.error.InvalidAddressError
-"255.255.255.255" results in twisted.internet.error.CannotListenError: 
Couldn't listen on 255.255.255.255:1235: [Errno 49] Can't assign 
requested address.
- omitting it results in no packets received.
I also tried listenMulticast, but it didn't work (and I didn't expect it 
to, based on comments I saw on the ticket for implementing UDP broadcast 
support).

Any hints would be appreciated.

#!/usr/bin/env python2
"""Attempt to listen to UDP broadcasts
"""
from twisted.internet.protocol import DatagramProtocol
from twisted.internet import reactor

Port = 1235

class BroadcastUDPClient(DatagramProtocol):
    def startProtocol(self):
        self.transport.setBroadcastAllowed(True)

    def datagramReceived(self, datagram, address):
        print "got a UDP broadcast packet"

class UDPListener(object):
    def __init__(self, port):
        self.port = port
        self.broadcastClient = BroadcastUDPClient()
        self.listener = None
        self.startListening()

    def startListening(self):
        if self.listener is None:
            interface = "255.255.255.255"
            self.listener = reactor.listenUDP(self.port,
                self.broadcastClient, interface)

    def stopListening(self):
        if self.listener is not None:
            self.listener.stopListening()
            self.listener = None

if __name__ == "__main__":
    listener = UDPListener(Port)
    reactor.run()




More information about the Twisted-Python mailing list