using System;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;
public class WakeOnLan
{
public static void WakeUp(string macAddress, string broadcastIp = "255.255.255.255", int port = 4343)
{
// 驗證MAC地址格式并轉換為字節數組
byte[] macBytes = ParseMacAddress(macAddress);
// 構建魔術包(6x0xFF + 16xMAC地址)
byte[] packet = new byte[17 * 6];
for (int i = 0; i < 6; i++)
{
packet[i] = 0xFF;
}
for (int i = 1; i <= 16; i++)
{
Buffer.BlockCopy(macBytes, 0, packet, i * 6, 6);
}
// 使用UDP發送到廣播地址
using (UdpClient client = new UdpClient())
{
client.EnableBroadcast = true;
IPEndPoint endpoint = new IPEndPoint(IPAddress.Parse(broadcastIp), port);
client.Send(packet, packet.Length, endpoint);
}
}
private static byte[] ParseMacAddress(string macAddress)
{
// 移除分隔符
string cleanMac = macAddress
.Replace(":", "")
.Replace("-", "")
.Replace(".", "")
.Trim();
// 驗證長度(12個字符)
if (cleanMac.Length != 12)
throw new ArgumentException("Invalid MAC address format");
// 轉換為字節數組
byte[] bytes = new byte[6];
for (int i = 0; i < 6; i++)
{
string byteStr = cleanMac.Substring(i * 2, 2);
bytes[i] = Convert.ToByte(byteStr, 16);
}
return bytes;
}
}
// 使用示例
public class Program
{
public static void Main()
{
try
{
// 替換為目標電腦的MAC地址
string macAddress = "01-23-45-67-89-AB";
// 可選:指定正確的廣播地址(如 "192.168.1.255")
WakeOnLan.WakeUp(macAddress);
Console.WriteLine("喚醒信號已發送");
}
catch (Exception ex)
{
Console.WriteLine($"錯誤: {ex.Message}");
}
}
}