Wake-on-LAN (WOL) from C#?

We got a request today from someone wondering if the SDF would help send a Wake-on-LAN or Magic Packet.  Well I’ve never had to do it before, so I looked it up on Wikipedia. The short answer is no, but that’s because all of the required pieces are already there in the CF.

Here’s my guess on it – keep in mind that I don’t have a WOL-capable PC lying around to test this with (if you test it and can confirm if it does or does not work, by all means let me know).

UPDATE (Dec 7, 06): Alex Feinman took the time to test the original code and the broadcast didn’t work.  The code has been updated with working, tested code.

/// <summary>
/// Wakes a remote PC
/// </summary>
/// <param name=”targetMAC”>MAC address of target. Must be 6 bytes and MUST be in network order (reversed)</param>
/// <param name=”password”>Optional password. Must be null or 4 or 6 bytes.</param>
public static void WOL(byte[] targetMAC, byte[] password)
  // target mac must be 6-bytes!
  if (targetMAC.Length != 6)
    throw new ArgumentException();

  // check password
  if((password != null) && 
      (password.Length != 4) && 
      (password.Length != 6))
    throw new ArgumentException();

  int packetLength = 6 + (20 * 6);
  if (password != null)
    packetLength += password.Length;

[] magicPacket = new byte[packetLength];

  // has a 6-byte header of 0xFF
  byte[] header = new byte[] { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
  Buffer.BlockCopy(header, 0, magicPacket, 0, header.Length);

  // repeat the destination MAC 16 times

  // your MAC *is* in network (reverse) order, right??
offset = 6;
  for(int i = 0 ; i < 16 ; i++)
    Buffer.BlockCopy(targetMAC, 0, magicPacket, offset, targetMAC.Length);
    offset += 6;

  if (password != null)
    Buffer.BlockCopy(password, 0, magicPacket, offset, password.Length);

  IPEndPoint ep = new IPEndPoint(IPAddress.Broadcast, 9);
  UdpClient c = new UdpClient();
c.Send(magicPacket, magicPacket.Length, ep);

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s