Sunday, June 20, 2010

Wake-on-LAN using C#

I recently set my personal computer to sleep after 30 minutes of inactivity. This seemed reasonable since I was normally only on the computer for a few hours a day.

I quickly realized that when I tried to remote desktop into it, if the computer was asleep it wouldn't connect (duh). I then modified the network interface settings to Wake-on-LAN and enhanced the security a bit by only waking on a "magic packet".

Then I wrote a interface where I can visit a web page and send the "magic packet" to my computer in order to wake it up. I won't go into the whole interface, but the code below demonstrates how to send the "magic packet" from C#. See the wiki article on details about what the "magic packet" is:

http://en.wikipedia.org/wiki/Wake-on-LAN

Also, don't forget to open any inbound or outbound ports on your firewall!

private void SendMagicPacket(string destinationHost, int destinationPort)
{
   // the header frame of 6 bytes of 255
   List<byte> datagram = new List<byte> { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };

   // load the mac address (for demo purposes, set it to zeros)
   byte[] macAddress = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };

   // 16 sequences of the MAC address
   for (int i = 0; i < 16; ++i)
   {
      datagram.AddRange(macAddress);
   }

   //
   // you don't have to do both below, but both are shown
   //

   // send directly to an IP address
   using (UdpClient client = new UdpClient())
   {
      client.Connect(destinationHost, destinationPort);
      client.Send(datagram.ToArray(), datagram.Count);
   }

   // broadcast it
   using (UdpClient client = new UdpClient())
   {
      client.Connect(IPAddress.Broadcast, destinationPort);
      client.Send(datagram.ToArray(), datagram.Count);
   }
}

No comments:

Can't RDP? How to enable / disable virtual machine firewall for Azure VM

Oh no!  I accidentally blocked the RDP port on an Azure virtual machine which resulted in not being able to log into the VM anymore.  I did ...