Wednesday, March 16, 2011

[Dev] Wake On Lan or in short WOL, a C# code snippet

Today a colleague asked me about sending a WOL message to wake up a networked computer. Coincidently I am working on an energy saving application that wakes up my media server when needed via a magic packet.

The next piece of C# code  takes care of the creation and the broadcast of the packet:
public void SendMagicPacket()
{
 // The MAC address of the computer which needs to wake up.
 byte[] macAddress = new byte[] { 0x00, 0x19, 0x66, 0xa0, 0x75, 0xb2 };

 // Create the packet.
 List<byte> packet = new List<byte>();

 // The packet start with 6 0xFF packets.
 for (int i = 0; i < 6; i++)
 {
  packet.Add(0xFF);
 }

 // Then the MAC address is repeated 16 times.
 for (int i = 0; i < 16; i++)
 {
  packet.AddRange(macAddress);
 }

 // Finally we send the packet to the broadcast address.
 UdpClient client = new UdpClient();
 client.Connect(IPAddress.Broadcast, 7); 
 client.Send(packet.ToArray(), packet.Count);
 client.Close();
}

Make sure that the computer which needs to wake up is correctly configured in the BIOS. As I understand certain Broadcom network cards have trouble waking up, so be warned.

No comments:

Post a Comment