Receiving Broadcast Packets in Python

Question:

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?

Asked By: nitish712

||

Answers:

Try binding to the default address:

s.bind(('',12345))
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:10.0.2.2 Bcast:10.0.2.255 Mask:255.255.255.0


then the server should use
s.bind((‘10.0.2.255’,12345)), not 10.0.2.2 (in OP’s case he should use 255.255.255.255).
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
s=socket(AF_INET, SOCK_DGRAM)
s.bind(('',1234))
while(1):
    m=s.recvfrom(4096)
    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.