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}");
        }
    }
}