Sending a broadcast message using raw sockets

Rob Williscroft rtw at rtw.me.uk
Mon Jan 21 04:10:06 EST 2013


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 ':'.

http://en.wikipedia.org/wiki/Wake-on-LAN



Rob.




More information about the Python-list mailing list