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.
68 lines
1.6 KiB
68 lines
1.6 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 static readonly int WOL_PACKET_LEN = 102;
|
|
private static readonly int[] DEFAULT_PORTS = new int[] { 7, 9 };
|
|
|
|
public static void Wake(string ip, string macAddress, int[] ports = null)
|
|
{
|
|
byte[] wolBuffer = GetWolPacket(macAddress);
|
|
|
|
UdpClient udp = new UdpClient();
|
|
udp.EnableBroadcast = true;
|
|
|
|
IPAddress ipAddress = Utils.GetIpAddress(ip);
|
|
if (ports == null || ports.Length < 1)
|
|
ports = DEFAULT_PORTS;
|
|
|
|
foreach (int port in ports)
|
|
{
|
|
udp.Send(wolBuffer, wolBuffer.Length, ipAddress.ToString(), port);
|
|
}
|
|
}
|
|
|
|
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;
|
|
}
|
|
}
|
|
}
|
|
|