start another pc via wake-on-lan in csharp

Here's an example of how to use wake-on-lan in c#:

main.cs
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;

public static class WakeOnLan
{
    public static void SendMagicPacket(string macAddress)
    {
        var macAddressParts = macAddress.Split(':');

        if (macAddressParts.Length != 6)
            throw new ArgumentException("Incorrect MAC address format", nameof(macAddress));

        var macBytes = new byte[6];

        for (var i = 0; i < 6; i++)
            macBytes[i] = Convert.ToByte(macAddressParts[i], 16);

        var wakeUpPacket = new byte[102];

        for (var i = 0; i < 6; i++)
            wakeUpPacket[i] = 0xFF;

        for (var i = 6; i < 102; i += 6)
            Array.Copy(macBytes, 0, wakeUpPacket, i, 6);

        using (var client = new UdpClient())
            client.Send(wakeUpPacket, wakeUpPacket.Length, new IPEndPoint(IPAddress.Broadcast, 0));
    }
}

public static void Main()
{
    var macAddress = "00:11:22:33:44:55";
    WakeOnLan.SendMagicPacket(macAddress);
}
992 chars
38 lines

This code sends a wake-on-lan magic packet to a specified MAC address. The magic packet is broadcast on the local network to wake up a remote computer from a sleeping state.

gistlibby LogSnag