Receiving Broadcast Packets in Python


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

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

The following code is for receiving the broadcast packet.

from socket import *
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?

Asked By: nitish712



Try binding to the default address:

Answered By: John Zwinck

I believe the solution outlined in the accepted answer solves the issue, but not in exactly the right way. You shouldn’t use the normal interface IP, but the broadcast IP which is used to send the message. For example if ifconfig is:

inet addr: Bcast: Mask:

then the server should use
s.bind((‘’,12345)), not (in OP’s case he should use
The reason the accepted answer works is because ‘ ‘ tells the server to accept packets from all addresses, while specifying the IP address, filters it.

‘ ‘ is the hammer, specifying the correct broadcast address is the scalpel. And in many cases, though possibly not OP’s, it is important that a server listen only the specified IP address (e.g. you want to accept requests only from a private network – the above code would accept requests from any external network too), for security purposes if nothing else.

Answered By: Abraham Philip
    print 'len(m)='+str(len(m))
    print 'len(m[0])='+str(len(m[0]))    
    print m[0]

    print 'len(m[1])='+str(len(m[1]))    
    print m[1]  
Answered By: MinhNV
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.