Reputation: 19774
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?
Upvotes: 33
Views: 58467
Reputation: 668
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:
Upvotes: 23
Reputation: 325
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]
Upvotes: 1