Scanning for local servers, getting a broadcast address

Noah noah at
Mon Jun 9 17:25:27 CEST 2003

chris.lyon at (Chris Lyon) wrote in message news:<d232c5e.0306090158.6d3c99d6 at>...
> ...
> However since I have to generate the broadcast address, I need to know
> at least my subnet mask to allow me to derive the Broadcast address.
> How do I do this in a pythonic fashion without recourse to reading
> host files which seems very platform dependant?
> ...
> Chris Lyon

Do you really need to get the subnet mask? Can you just use the special
'<broadcast>' address? The following code (client and server test)
demonstrate broadcasting without having to find the subnet mask.
Run them on different machines on the same subnet and you should see
the server print the packets from the client.

--- ----------------------------------------------------------------
import time
import socket
s = socket.socket (socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
s.setsockopt (socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
while 1:
        s.sendto('hello\n', ('<broadcast>', 2003))

--- ----------------------------------------------------------------
import socket
import select
import sys
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
s.bind( ('', 2003) )
while 1:
        if s in rfd:
                (string, address) = s.recvfrom(100)
                print 'string: %s' % string
                print 'from: %s' % str(address)
                print '--------------------------------'


More information about the Python-list mailing list