Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - UDP socket bind() to the correct address

I can't understand why if I create a socket in this way

from socket import *
s = socket(AF_INET, SOCK_DGRAM)
s.bind(("192.168.1.10",26000))
print s.recvfrom(4096)[0]

and I try to send to it a broadcast packet like this

from socket import *
s = socket(AF_INET, SOCK_DGRAM)
s.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
s.sendto("hey!", ("<broadcast>", 26000))

it doesn't work (it hangs on the recvfrom()) but if I try to bind it to "0.0.0.0" it receives the packet correctly.

I know that 0.0.0.0 means that every address on every interface will be listening on that port, but why binding directly to an address makes it don't receive the packet?

Operating system: OSX 10.9.2, Python version: 2.7.6

Even if I'm not running Linux, I tried binding the socket to the subnet broadcast address anyway, same results.

like image 585
Kava Avatar asked Oct 20 '22 10:10

Kava


1 Answers

If the operating system is Linux then try to bind socket to the subnet broadcast address. For example, if your ifconfig settings are inet addr:192.168.0.62 Bcast:192.168.0.255 Mask:255.255.255.0then bind your receiver socket to 192.168.0.255. On Linux you won't be able to use your regular IP address

There is a previous discussion on the topic here

like image 155
Konstantin Avatar answered Oct 23 '22 01:10

Konstantin