You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
62 lines
1.4 KiB
62 lines
1.4 KiB
using System;
|
|
using System.Globalization;
|
|
using System.IO;
|
|
using System.Net;
|
|
using System.Net.Sockets;
|
|
using System.Text.RegularExpressions;
|
|
|
|
namespace WakeOnLan
|
|
{
|
|
public class WoL
|
|
{
|
|
private const int WOL_PACKET_LEN = 102;
|
|
|
|
public static void Wake(string ip, string macAddress)
|
|
{
|
|
byte[] wolBuffer = GetWolPacket(macAddress);
|
|
|
|
UdpClient udp = new UdpClient();
|
|
udp.EnableBroadcast = true;
|
|
|
|
IPAddress ipAddress = IPAddress.Parse(ip);
|
|
udp.Send(wolBuffer, wolBuffer.Length, ipAddress.ToString(), 7);
|
|
udp.Send(wolBuffer, wolBuffer.Length, ipAddress.ToString(), 9);
|
|
}
|
|
|
|
private static byte[] GetWolPacket(string macAddress)
|
|
{
|
|
byte[] datagram = new byte[WOL_PACKET_LEN];
|
|
byte[] macBuffer = StringToBytes(macAddress);
|
|
|
|
using (MemoryStream ms = new MemoryStream(datagram))
|
|
{
|
|
BinaryWriter bw = new BinaryWriter(ms);
|
|
for (int i = 0; i < 6; i++)
|
|
{
|
|
bw.Write((byte)0xff);
|
|
}
|
|
|
|
for (int i = 0; i < 16; i++)
|
|
{
|
|
bw.Write(macBuffer, 0, macBuffer.Length);
|
|
}
|
|
}
|
|
|
|
return datagram;
|
|
}
|
|
|
|
private static byte[] StringToBytes(string macAddress)
|
|
{
|
|
macAddress = Regex.Replace(macAddress, "[-|:]", "");
|
|
byte[] buffer = new byte[macAddress.Length / 2];
|
|
|
|
for (int i = 0; i < macAddress.Length; i += 2)
|
|
{
|
|
string digit = macAddress.Substring(i, 2);
|
|
buffer[i / 2] = byte.Parse(digit, NumberStyles.HexNumber);
|
|
}
|
|
|
|
return buffer;
|
|
}
|
|
}
|
|
}
|
|
|