Welcome, guest | Sign In | My Account | Store | Cart

simplest implementation I could achieve

Python, 13 lines
 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.

2 comments

Conrad Spiteri 12 years, 1 month ago  # | flag

Thanks for the code Matt, It was very useful. Thanks for sharing

Conrad (UWE)

Ben 11 years, 10 months ago  # | flag

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.