Receiving Broadcast Packets in Python

nitish712 picture nitish712 · Apr 5, 2014 · Viewed 37.2k times · Source

I have the following code which sends a udp packet that is broadcasted in the subnet.

from socket import *
s=socket(AF_INET, SOCK_DGRAM)
s.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
s.sendto('this is testing',('255.255.255.255',12345))

The following code is for receiving the broadcast packet.

from socket import *
s=socket(AF_INET, SOCK_DGRAM)
s.bind(('172.30.102.141',12345))
m=s.recvfrom(1024)
print m[0]

The problem is that its not receiving any broadcast packet. However, it is successfully receiving normal udp packets sent to that port.

My machine was obviously receiving the broadcast packet, which I tested using netcat.

$ netcat -lu -p 12345                                             
this is testing^C

So, where exactly is the problem?

Answer

John Zwinck picture John Zwinck · Apr 5, 2014

Try binding to the default address:

s.bind(('',12345))