Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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=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?

like image 742
nitish712 Avatar asked Apr 05 '14 08:04

nitish712


2 Answers

Try binding to the default address:

s.bind(('',12345)) 
like image 102
John Zwinck Avatar answered Oct 12 '22 05:10

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.
like image 32
Abraham Philip Avatar answered Oct 12 '22 05:10

Abraham Philip