首页 > 代码库 > C#网络唤醒

C#网络唤醒

  1. public partial class MainWindow : Window
  2. {
  3. //通过正则表达式设定MAC地址筛选标准,关于正则表达式请自行百度
  4. const string macCheckRegexString = @"^([0-9a-fA-F]{2})(([/\s:-][0-9a-fA-F]{2}){5})$";
  5. private static readonly Regex MacCheckRegex = new Regex(macCheckRegexString);
  6. public MainWindow()
  7. {
  8. InitializeComponent();
  9. }
  10. //唤醒主要逻辑方法
  11. public static bool WakeUp(string mac)
  12. {
  13. //查看该MAC地址是否匹配正则表达式定义,(mac,0)前一个参数是指mac地址,后一个是从指定位置开始查询,0即从头开始
  14. if (MacCheckRegex.IsMatch(mac, 0))
  15. {
  16. byte[] macByte = FormatMac(mac);
  17. WakeUpCore(macByte);
  18. return true;
  19. }
  20. return false;
  21. }
  22. private static void WakeUpCore(byte[] mac)
  23. {
  24. //发送方法是通过UDP
  25. UdpClient client = new UdpClient();
  26. //Broadcast内容为:255,255,255,255.广播形式,所以不需要IP
  27. client.Connect(System.Net.IPAddress.Broadcast, 50000);
  28. //下方为发送内容的编制,6遍“FF”+17遍mac的byte类型字节。
  29. byte[] packet = new byte[17 * 6];
  30. for (int i = 0; i < 6; i++)
  31. packet[i] = 0xFF;
  32. for (int i = 1; i <= 16; i++)
  33. for (int j = 0; j < 6; j++)
  34. packet[i * 6 + j] = mac[j];
  35. //唤醒动作
  36. int result = client.Send(packet, packet.Length);
  37. }
  38. private static byte[] FormatMac(string macInput)
  39. {
  40. byte[] mac = new byte[6];
  41. string str = macInput;
  42. //消除MAC地址中的“-”符号
  43. string[] sArray = str.Split(‘-‘);
  44. //mac地址从string转换成byte
  45. for (var i = 0; i < 6; i++)
  46. {
  47. var byteValue = Convert.ToByte(sArray[i], 16);
  48. mac[i] = byteValue;
  49. }
  50. return mac;
  51. }
  52. private void Button_Click_1(object sender, RoutedEventArgs e)
  53. {
  54. WakeUp("00-01-80-7E-C3-D2");
  55. }
  56. }




null


C#网络唤醒