C# Wake on Lan (WOL) Packet

10. February 2011 18:34

Sending a wake on lan packet from c# can actually be very easy.

Using the following class it make it even easyier. All you need to know is the mac address of the machine you are attempt to wakeup.

public static void WakeUp(string MAC_ADDRESS, IPAddress IPBCast)
            UdpClient UDP = new UdpClient();

                UDP.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
                int offset = 0;
                byte[] buffer = new byte[512];   // more than enough :-)

                //first 6 bytes should be 0xFF
                for (int y = 0; y < 6; y++)
                    buffer[offset++] = 0xFF;

                //now repeate MAC 16 times
                for (int y = 0; y < 16; y++)
                    int i = 0;
                    for (int z = 0; z < 6; z++)
                        buffer[offset++] =
                            byte.Parse(MAC_ADDRESS.Substring(i, 2), NumberStyles.HexNumber);
                        i += 2;

                UDP.EnableBroadcast = true;
                UDP.Send(buffer, 512, new IPEndPoint(IPBCast, 0x1));
            catch (Exception ex)
                throw (ex);

All you need todo is call the function with a valid MAC address and a broadcast ip address. In most cases will work. However if you want to broadcast across a certain remote network on another subnet you may need to user X.X.255.255 for example. Otherwise the packet will not be routed to the correct network.

E-mail Kick it! DZone it! del.icio.us Permalink