Search code examples
c#network-programmingethernetwake-on-lan

How to broadcast WOL over ethernet without enabling IP directed broadcast


I am building a Wake On Lan program in C# i have found lots of code for WOL but whatever i have found thus far does not work. i believe this is because i cannot enable IP directed broadcast (The customer's security policy will not enable this in order to prevent DOS attacks).

i am looking for a way to send the magic packet over ethernet directly to the requested mac address - right now it seems to be sending over UDP to 255.255.255.255

(What i am don't understand is why it needs to send to 255.255.255.255 and not to the mac itself)

here is the code i have as of now (can't remember where i found it).

public static bool WakeOnLan(string MacAddress)
{
    try
    {
        MacAddress = MacAddress.Replace("-", "");
        MacAddress = MacAddress.Replace(":", "");
        if (MacAddress.Length != 12)
        {
            return false;
        }
        byte[] mac = new byte[6];
        for (int k = 0; k < 6; k++)
        {
            mac[k] = Byte.Parse(MacAddress.Substring(k * 2, 2), System.Globalization.NumberStyles.HexNumber);
        }

        // WOL packet is sent over UDP 255.255.255.0:40000.
        System.Net.Sockets.UdpClient client = new System.Net.Sockets.UdpClient();
        client.Connect(System.Net.IPAddress.Broadcast, 4000);

        byte[] packet = new byte[17 * 6];

        for (int i = 0; i < 6; i++)
            packet[i] = 0xFF;

        for (int i = 1; i <= 16; i++)
            for (int j = 0; j < 6; j++)
                packet[i * 6 + j] = mac[j];

        client.Send(packet, packet.Length);
        return true;
    }
    catch
    {
        return false;
    }
}

Any help would be greatly appreciated.

thanx


Solution

  • WoL frames are sent to the broadcast MAC address, ffff:ffff:ffff. To do that, you must send the IP packet to either the network or limited broadcast address. Broadcasts do not cross routers because this is a huge security hole.

    Implementation that must send WoL from different network do this by placing a WoL server on the LAN, and send commands to the WoL server that will then send WoL frames on the LAN.


    Edit:

    If you are trying to do WoL with the source and destination on the same LAN, you can use either the LAN or limited broadcast because the frames will not try to cross a router.

    You really should not use UDP. This can be accomplished with an ethernet frame. Just send the frame to ffff:ffff:ffff. IP addresses are only needed to get a packet from one network to another network. Data on a LAN is delivered in layer-2, e.g. ethernet, frames.

    You can just use an EtherType of 0x0842, then in the frame payload, put in 0xffffffffffff followed immediately by 16 repetitions of the target MAC address. That is all that is necessary for a "Magic Packet" because it is really a frame, not a packet.