Scanning for local servers, getting a broadcast address

Noah noah at noah.org
Mon Jun 9 11:25:27 EDT 2003


chris.lyon at spritenote.co.uk (Chris Lyon) wrote in message news:<d232c5e.0306090158.6d3c99d6 at posting.google.com>...
> ...
> 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.

--- bclient.py ----------------------------------------------------------------
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))
        time.sleep(1)

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

Yours,
Noah




More information about the Python-list mailing list