Uncategorized

Wake-on-LAN (WOL) with C#

I am sure you have heard of Wake-on-LAN, or at least you have read it in one of the older BIOSes. It is a technology that allows you to power on your system. When WOL is fully functioning, you should be able to switch on your PC by sending a specific packet to the network adapter: The Magic Packet.

In a video I published on YouTube, you can see this in action. We used the web interface of my router to send this Magic Packet, but later, we also sent it via a small application written in C#. The code can be adapted to another programming language of your choice, but I went with C# as this is the language I am most familiar with.

Here is the code to send a Magic Packet – please note that I have changed the broadcast IP address to 255.255.255.255 – which would mean ALL devices on the network. Please change the placeholders ("TARGET DEVICE MAC ADDRESS", "BROADCAST IP") in the code with the values required for your setup.

private static readonly string[] MAGIC_PACKET = new string[17]
{
    "FF-FF-FF-FF-FF-FF",
    "TARGET DEVICE MAC ADDRESS",
    "TARGET DEVICE MAC ADDRESS",
    "TARGET DEVICE MAC ADDRESS",
    "TARGET DEVICE MAC ADDRESS",
    "TARGET DEVICE MAC ADDRESS",
    "TARGET DEVICE MAC ADDRESS",
    "TARGET DEVICE MAC ADDRESS",
    "TARGET DEVICE MAC ADDRESS",
    "TARGET DEVICE MAC ADDRESS",
    "TARGET DEVICE MAC ADDRESS",
    "TARGET DEVICE MAC ADDRESS",
    "TARGET DEVICE MAC ADDRESS",
    "TARGET DEVICE MAC ADDRESS",
    "TARGET DEVICE MAC ADDRESS",
    "TARGET DEVICE MAC ADDRESS",
    "TARGET DEVICE MAC ADDRESS"
};

private static readonly string BROADCAST_IP = "BROADCAST IP";

static void Main(string[] args)
{
    Console.WriteLine($"Your broadcast IP: {IPAddress.Parse(BROADCAST_IP)}");
    Console.WriteLine($"The MAC address to wake up is: {MAGIC_PACKET[1]}");
    Console.WriteLine(string.Empty);
    Console.Write($"Press any key to send the MAGIC PACKET...");
    Console.Read();

    Console.WriteLine(string.Empty);
    Console.WriteLine($"Sending broadcast to {IPAddress.Broadcast}...");
    SendWakeOnLan(PhysicalAddress.Parse(MAGIC_PACKET[1]));
    Console.Write("Done! Press any key to exit...");

    _ = Console.ReadKey();
}

static void SendWakeOnLan(PhysicalAddress target)
{
    byte[] toByteArray(string[] addressBytes) => addressBytes.Select(b => Convert.ToByte(b, 16)).ToArray();

    var magicPacket = MAGIC_PACKET.SelectMany(macAddress => toByteArray(macAddress.Split('-', ':'))).ToArray();
    using (var client = new UdpClient())
    {
        client.Send(magicPacket, magicPacket.Length, new IPEndPoint(IPAddress.Parse(BROADCAST_IP), 9));
    }
}

To find the broadcast IP of your subnet, you can either do that yourself (maybe with the help of this Wikipedia article), or you can use this Excel sheet. For more details, please watch the video I posted on YouTube.

Broadcast IP Excel

Leave a Reply

Your email address will not be published. Required fields are marked *