Wednesday, March 6, 2019

Wake on Lan

using System;
using System.Web;
using System.Web.Script.Serialization;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Net;
using System.IO;
using System.Collections;
using System.Text;
using Newtonsoft.Json;
using Microsoft.VisualBasic;
using System.Diagnostics;
using System.Text.RegularExpressions;
using Newtonsoft.Json.Linq;
using System.Globalization;
using System.Net.Sockets;


public class WOLUdpClient : UdpClient
{
    // *********************************************************************
    /// <summary>
    /// Initializes a new instance of <see cref="WOLUdpClient"/>.
    /// </summary>
    public WOLUdpClient()
        : base()
    {
    }

    // *********************************************************************
    /// <summary>
    /// Sets up the UDP client to broadcast packets.
    /// </summary>
    /// <returns><see langword="true"/> if the UDP client is set in
    /// broadcast mode.</returns>
    public bool IsClientInBrodcastMode()
    {
        bool broadcast = false;
        if (this.Active)
        {
            try
            {
                this.Client.SetSocketOption(SocketOptionLevel.Socket,
                     SocketOptionName.Broadcast, 0);
                broadcast = true;
            }
            catch
            {
                broadcast = false;
            }
        }
        return broadcast;
    }
}

 private String GetClientMac(string IPAddress)
    {
        /* There is a good chance that the server does not have an "arp" record for a given IP address, */
        /* so to create an arp entry we first send a ping to the IP Address*/
        string mac = string.Empty;

        try
        {
            //Sending ping:
            ProcessStartInfo psi = new ProcessStartInfo();
            psi.FileName = "ping";
            psi.CreateNoWindow = true;
            psi.RedirectStandardInput = false;
            psi.RedirectStandardOutput = false;
            psi.Arguments = IPAddress;
            psi.UseShellExecute = false;

            Process process = Process.Start(psi);
            process.WaitForExit();

            //Now run arp command:
            psi = new ProcessStartInfo();
            psi.FileName = "arp";
            psi.CreateNoWindow = false;
            psi.RedirectStandardInput = false;
            psi.RedirectStandardOutput = true;
            psi.Arguments = "-a " + IPAddress;
            psi.UseShellExecute = false;

            process = Process.Start(psi);
            string arpInfo = string.Empty;
            while (!process.StandardOutput.EndOfStream)
            {
                arpInfo += process.StandardOutput.ReadLine();
            }

            process.WaitForExit();

            //Remove all white space from ARP result:
            arpInfo = arpInfo.Replace(" ", "");
            //Strip MAC from ARP result
            mac = arpInfo.Substring((arpInfo.IndexOf(IPAddress) + IPAddress.Length), 17);
        }
        catch (Exception)
        {
            //Error code here....
        }

        return mac.ToUpper();
    }


 private static string Wakeup(string macAddress)
    {
        try
        {
            WOLUdpClient client = new WOLUdpClient();
            client.Connect(
            new IPAddress(0xffffffff),    //255.255.255.255  i.e broadcast
            0x2fff); // port = 12287
            if (client.IsClientInBrodcastMode())
            {
                int byteCount = 0;
                byte[] bytes = new byte[102];
                for (int trailer = 0; trailer < 6; trailer++)
                {
                    bytes[byteCount++] = 0xFF;
                }
                for (int macPackets = 0; macPackets < 16; macPackets++)
                {
                    int i = 0;
                    for (int macBytes = 0; macBytes < 6; macBytes++)
                    {
                        bytes[byteCount++] =
                        byte.Parse(macAddress.Substring(i, 2),
                        NumberStyles.HexNumber);
                        i += 2;
                    }
                }

                int returnValue = client.Send(bytes, byteCount);
                return (returnValue + " bytes sent to " + macAddress +
                 Environment.NewLine + "Check if it's woken up. If not, try again!" +
                 Environment.NewLine);
            }

            else
            {
                return ("Remote client could not be set in broadcast mode!");
            }
        }
        catch (Exception e)
        {
            return e.Message;
        }
    }

string MAC = "00-00-0000-0000".Replace("-", "");
 Wakeup(MAC);

No comments:

Post a Comment