共用方式為


Wake-On-Lan Client with C#

I bought myself an Acer L5100 Media Center PC, running with Windows Vista Media Center for Christmas.

What I wanted was some functionality to wake up the media center out of shutdown mode. So I dig into Wake-On-Lan.

Almost any modern network interface controller (NIC) supports Wake-On-Lan nowadays. You just send a special packet as a broadcast containing the layer2 MAC address of the NIC and it will boot up the computer immediately.

So I tried to write my own WOL client with C#. And it turned out it’s pretty easy.

 public static class WakeOnLan
{
    public static void WakeUp(string macAddress, string ipAddress, string subnetMask)
    {
        UdpClient client = new UdpClient();

        Byte[] datagram = new byte[102];

        for (int i = 0; i <= 5; i++)
        {
            datagram[i] = 0xff;
        }

        string[] macDigits = null;
        if (macAddress.Contains("-"))
        {
            macDigits = macAddress.Split('-');
        }
        else
        {
            macDigits = macAddress.Split(':');
        }

        if (macDigits.Length != 6)
        {
            throw new ArgumentException("Incorrect MAC address supplied!");
        }

        int start = 6;
        for (int i = 0; i < 16; i++)
        {
            for (int x = 0; x < 6; x++)
            {
                datagram[start + i * 6 + x] = (byte)Convert.ToInt32(macDigits[x], 16);
            }
        }

        IPAddress address = IPAddress.Parse(ipAddress);
        IPAddress mask = IPAddress.Parse(subnetMask);
        IPAddress broadcastAddress = address.GetBroadcastAddress(mask);

        client.Send(datagram, datagram.Length, broadcastAddress.ToString(), 3);
    }
}

All you need to do is create a packet with 6 times 0xFF at the beginning.

Then send 16 times the mac address of the machine you want to wake up.

This is done with the UdpClient class of the .NET Framework.

The target address of the packet is the broadcast address of the network, which I calculate with the help of the IPAddress Extensions from the earlier blog post.

Feel free to download the sources here.

WakeOnLan.zip

Comments

  • Anonymous
    December 30, 2008
    PingBack from http://www.codedstyle.com/wake-on-lan-client-with-c/

  • Anonymous
    March 22, 2009
    do you have a special version of .NET? Where do you presume the method GetBroadcastAddress of IPAddress is defined?

  • Anonymous
    May 04, 2009
    I'm on a VOIP system now and wol doesn't work like it used to. It seems that turning off broadcast is the solution. How would you handle the C# code in this situation?