Sending a broadcast message using raw sockets

Peter Steele pwsteele at gmail.com
Tue Jan 22 02:06:02 CET 2013


On Monday, January 21, 2013 1:10:06 AM UTC-8, Rob Williscroft wrote:
> Peter Steele wrote in
> 
> news:f37ccb35-8439-42cd-a063-962249b44903 at googlegroups.com in
> 
> comp.lang.python: 
> 
> > I want to write a program in Python that sends a broadcast message
> > using raw sockets. The system where this program will run has no IP or
> > default route defined, hence the reason I need to use a broadcast
> > message. 
> > 
> > I've done some searches and found some bits and pieces about using raw
> > sockets in Python, but I haven't been able to find an example that
> > explains how to construct a broadcast message using raw sockets. 
> > 
> > Any pointers would be appreciated.
> 
> This is part of my Wake-On-Lan script:
> 
> def WOL_by_mac( mac, ip = '<broadcast>', port = 9 ):
> 
>   import struct, socket
> 
>   a = mac.replace( ':', '-' ).split( '-' )
>   addr = struct.pack( 'B'*6, *[ int(_, 16) for _ in a ] )
>   msg = b'\xff' * 6 + addr * 16
> 
>   s = socket.socket( socket.AF_INET, socket.SOCK_DGRAM )
>   s.setsockopt( socket.SOL_SOCKET, socket.SO_BROADCAST, 1 )
>   s.sendto( msg, ( ip, port ) )
>   s.close()
> 
> The mac address is 6 pairs of hex digits seperated by '-' or ':'.

Thanks for the code sample. Does this code work if the box has no IP or default route assigned? I'm away from the office at the moment so I can't test this.



More information about the Python-list mailing list