Monday, January 24, 2011

Wake ON LAN (Simplified) in ASP .NET

Sometime last year I did a Wake ON LAN implementation on WinForms. This year I reimplemented it with Web.  Please view the simple method below. I implemented this in my MobileExec Program (see screenshot above):



private static void WakeUp(string mac, string broadcast)
    {
        string macAddr = mac;


        long value = long.Parse(macAddr, NumberStyles.HexNumber, CultureInfo.CurrentCulture.NumberFormat);
        byte[] macBytes = BitConverter.GetBytes(value);


        Array.Reverse(macBytes);
        byte[] macAddress = new byte[6];
        for (int i = 0; i <= 5; i++)
            macAddress[i] = macBytes[i + 2];


        List<byte> packet = new List<byte>();


        for (int i = 0; i < 6; i++)
            packet.Add(0xFF);


        for (int i = 0; i < 16; i++)
            packet.AddRange(macAddress);


        UdpClient client = new UdpClient();
        if (broadcast == "broad")
        {
            client.Connect(broadcast, 7);
            client.Send(packet.ToArray(), packet.Count);
        }
        else
        {
            client.Connect(IPAddress.Broadcast, 7);
            client.Send(packet.ToArray(), packet.Count);
        }
    }

No comments:

Post a Comment