problems using magic "<broadcast>" socket address on different platforms

Irmen de Jong irmen at -NOSPAM-REMOVETHIS-xs4all.nl
Sun Apr 27 09:05:29 EDT 2003


Hello
I'm trying to use UDP broadcasting but there are some weird things going
on regarding Python's magic "<broadcast>" address (which is
the INADDR_BROADCAST address).


Using the following piece of Python code to send UDP broadcast messages:

----
from socket import *

sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)
sock.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
sock.sendto("Het Bericht", ("<broadcast>", 2000) )
print "done"
----

This works fine. The problems are in the server code:

----
from socket import *
import select
import sys

sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)
sock.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
sock.bind( ("<broadcast>", 2000) )

while 1:
	(rs,ws,es)=select.select([sock],[],[],1)
	if sock in rs:
		(data, addr) = sock.recvfrom(9999)
		print "Got data: {%s}" % data
		print "from:",addr
	else:
		print ".",
		sys.stdout.flush()
----		

When running this on Linux, everything works as expected.
When running the server code on Windows, Python fails to bind
the socket on the magic "<broadcast>" address:
socket.error: (10049, "Can't assign requested address")

I've had reports of users that the same problem is present on Mac OS X.

Because I don't have access to other platforms than Windows (NT) and Linux,
I am wondering what the results are on other systems such as Solaris, *BSD...

--Irmen de Jong

PS 
The really weird part is that a piece of C code that directly uses the
BSD socket API *also* fails on windows with the same error
(bind: Cannot assign requested address, when trying to bind the socket
on the INADDR_BROADCAST address). The exact same piece of C code runs fine
on Linux. Used GCC in both cases. If you're interested in this code let me know,
I thought it was too big to post here.

PPS
To get my code to work on windows, I had to use the magic "" address
(INADDR_ANY). But I don't think that's right, "<broadcast>" should work,
shouldn't it?





More information about the Python-list mailing list