simplest implementation I could achieve
1 2 3 4 5 6 7 8 9 10 11 12 13 | import select, socket
port = 53005 # where do you expect to get a msg?
bufferSize = 1024 # whatever you need
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(('<broadcast>', port))
s.setblocking(0)
while True:
result = select.select([s],[],[])
msg = result[0][0].recv(bufferSize)
print msg
|
I couldn't find a working example which didn't use the excellent Twisted library, and that seemed too heavyweight for my needs. Here's a bare-bones process to listen for UDP broadcasts. The key is to set the socket non-blocking, and use the select module to wait until you can read from the socket. Hope it's useful to somebody.
Thanks for the code Matt, It was very useful. Thanks for sharing
Conrad (UWE)
The use of '<broadcast>' causes this code to fail. using '' (single quote pair, no content) makes it work.
However, the bind consumes the port, and prevents any other clients from receiving the broadcast.