小言_互联网的博客

c# 远程网络唤醒电脑(电脑远程开机+内网MAC和IP扫描)(附带源码+主板和Windows开启详细说明+外网远程唤醒方案)

500人阅读  评论(0)

一、需求

1、人在公司坐,昨晚写的文档放在家中电脑忘记Copy了,想要访问家中电脑拿到文档。

2、家中或公司中局域网内有某台电脑(或服务器)要开机,或者批量一键打开局域网内某些电脑

二、必备条件

1、网线连接电脑网口(wifi无线网卡无法网络唤醒)

2、网卡支持网络唤醒功能

三、设置

1、主板BIOS设置

目前测试过的主板:微星PRO Z690-A WIFI DDR4(MS-7D25)、技嘉B75M-D3V、技嘉B85M-D2V

下面以微星PRO Z690-A为例。

主板:微星PRO Z690-A WIFI DDR4

系统:Windows10

路由器:中兴AX5400,TPLink5600和7660

发包程序:C#,下面有源码,或者伸手党可以直接从下载链接获取发布好的应用程序

 开机狂按Del键进入微星BIOS,其他品牌DEL, ESC, F1, F2, F8, F9, F10, F12

  1. 高级–整合周边设备–网卡ROM启动,设置为允许
  2. 高级–电源管理设置–Eup 2013,设置为禁止
  3. 高级–唤醒事件设置–PCIE设备唤醒,设置为允许

2、网卡(Windows)设置

  1. 控制面板–所有控制面板项–网络连接
  2. 在网卡适配器点击鼠标右键–属性,弹出的属性对话框中
  3. 选择网络选项卡–配置
  4. 选择高级选项卡,将关机 网络唤醒设置为开启,将魔术封包唤醒设置为开启
  5. 电源管理选项卡,勾选下面三个选项,允许此设备唤醒计算机。
  6. 切换为电源管理选项,勾选允许此设备唤醒计算机。
  7. 关闭快速启动,右击开始按钮,点击“电源选项”,点击“选择电源按钮的功能”;点击“更改当前不可用的设置”,把“启用快速启动”勾选。(这条必须做

 

 

 

 3、后记

  1. 电脑网线连接网口处,电脑关机状态下有的会有黄灯常量,有的电脑不亮,都能唤醒
  2. 在设置网卡的时候发现没有关机 网络唤醒的选项的时候,有可能是网卡驱动或者网卡版本不同,没有此选项也能唤醒。

三、C#源码 

伸手党可以直接从下载链接获取发布好的应用程序,下载地址:

https://download.csdn.net/download/hwt0101/86781647


  
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Net;
  8. using System.Net.NetworkInformation;
  9. using System.Net.Sockets;
  10. using System.Runtime.InteropServices;
  11. using System.Text;
  12. using System.Text.RegularExpressions;
  13. using System.Threading.Tasks;
  14. using System.Windows.Forms;
  15. namespace RemotePowerOn
  16. {
  17. public partial class Form1 : Form
  18. {
  19. //通过正则表达式设定MAC地址筛选标准,关于正则表达式请自行百度
  20. const string macCheckRegexString = @"^([0-9a-fA-F]{2})(([/\s:-][0-9a-fA-F]{2}){5})$";
  21. private static readonly Regex MacCheckRegex = new Regex(macCheckRegexString);
  22. public Form1()
  23. {
  24. InitializeComponent();
  25. }
  26. public static bool WakeUp(string mac)
  27. {
  28. //查看该MAC地址是否匹配正则表达式定义,(mac,0)前一个参数是指mac地址,后一个是从指定位置开始查询,0即从头开始
  29. if (MacCheckRegex.IsMatch(mac, 0))
  30. {
  31. byte[] macByte = FormatMac(mac);
  32. WakeUpCore(macByte);
  33. return true;
  34. }
  35. return false;
  36. }
  37. private static void WakeUpCore(byte[] mac)
  38. {
  39. //发送方法是通过UDP
  40. UdpClient client = new UdpClient();
  41. //Broadcast内容为:255,255,255,255.广播形式,所以不需要IP
  42. client.Connect(System.Net.IPAddress.Broadcast, 40000);
  43. //下方为发送内容的编制,6遍“FF”+17遍mac的byte类型字节。
  44. byte[] packet = new byte[ 17 * 6];
  45. for ( int i = 0; i < 6; i++)
  46. packet[i] = 0xFF;
  47. for ( int i = 1; i <= 16; i++)
  48. for ( int j = 0; j < 6; j++)
  49. packet[i * 6 + j] = mac[j];
  50. //唤醒动作
  51. int result = client.Send(packet, packet.Length);
  52. }
  53. private static byte[] FormatMac(string macInput)
  54. {
  55. byte[] mac = new byte[ 6];
  56. string str = macInput;
  57. //消除MAC地址中的“-”符号
  58. string[] sArray = str.Split( '-');
  59. //mac地址从string转换成byte
  60. for ( var i = 0; i < 6; i++)
  61. {
  62. var byteValue = Convert.ToByte(sArray[i], 16);
  63. mac[i] = byteValue;
  64. }
  65. return mac;
  66. }
  67. private void button1_Click(object sender, EventArgs e)
  68. {
  69. string mac = textBox1.Text;
  70. WakeUp(mac);
  71. //WakeUp("25-D5-47-12-97-E2");
  72. }
  73. private void button2_Click(object sender, EventArgs e)
  74. {
  75. #region 方法1
  76. // TODO: Implement Functionality Here
  77. // Get my PC IP address
  78. Msg( string.Format( "My IP : {0}", GetIPAddress()));
  79. // Get My PC MAC address
  80. Msg( string.Format( "My MAC: {0}", GetMacAddress()));
  81. // Get My PC HostName
  82. Msg( string.Format( "My HostName: {0}", Dns.GetHostName()));
  83. // Get all devices on network
  84. Dictionary<IPAddress, PhysicalAddress> all = GetAllDevicesOnLAN();
  85. foreach (KeyValuePair<IPAddress, PhysicalAddress> kvp in all)
  86. {
  87. Msg( string.Format( "IP : {0}\n MAC {1}", kvp.Key, kvp.Value));
  88. }
  89. #endregion
  90. #region 方法2
  91. //GetIPAddress2();
  92. //foreach (var ip in ips)
  93. //{
  94. // //Console.WriteLine(ip);
  95. // Msg(ip);
  96. //}
  97. #endregion
  98. }
  99. #region MAC扫描方法1
  100. //public static void Main(string[] args)
  101. //{
  102. // Console.WriteLine("Hello World!");
  103. // // TODO: Implement Functionality Here
  104. // // Get my PC IP address
  105. // Console.WriteLine("My IP : {0}", GetIPAddress());
  106. // // Get My PC MAC address
  107. // Console.WriteLine("My MAC: {0}", GetMacAddress());
  108. // // Get My PC HostName
  109. // Console.WriteLine("My HostName: {0}", Dns.GetHostName());
  110. // // Get all devices on network
  111. // Dictionary<IPAddress, PhysicalAddress> all = GetAllDevicesOnLAN();
  112. // foreach (KeyValuePair<IPAddress, PhysicalAddress> kvp in all)
  113. // {
  114. // Console.WriteLine("IP : {0}\n MAC {1}", kvp.Key, kvp.Value);
  115. // }
  116. // Console.Write("Press any key to continue . . . ");
  117. // Console.ReadKey(true);
  118. //}
  119. /// <summary>
  120. /// MIB_IPNETROW structure returned by GetIpNetTable
  121. /// DO NOT MODIFY THIS STRUCTURE.
  122. /// </summary>
  123. [ StructLayout(LayoutKind.Sequential)]
  124. struct MIB_IPNETROW
  125. {
  126. [ MarshalAs(UnmanagedType.U4)]
  127. public int dwIndex;
  128. [ MarshalAs(UnmanagedType.U4)]
  129. public int dwPhysAddrLen;
  130. [ MarshalAs(UnmanagedType.U1)]
  131. public byte mac0;
  132. [ MarshalAs(UnmanagedType.U1)]
  133. public byte mac1;
  134. [ MarshalAs(UnmanagedType.U1)]
  135. public byte mac2;
  136. [ MarshalAs(UnmanagedType.U1)]
  137. public byte mac3;
  138. [ MarshalAs(UnmanagedType.U1)]
  139. public byte mac4;
  140. [ MarshalAs(UnmanagedType.U1)]
  141. public byte mac5;
  142. [ MarshalAs(UnmanagedType.U1)]
  143. public byte mac6;
  144. [ MarshalAs(UnmanagedType.U1)]
  145. public byte mac7;
  146. [ MarshalAs(UnmanagedType.U4)]
  147. public int dwAddr;
  148. [ MarshalAs(UnmanagedType.U4)]
  149. public int dwType;
  150. }
  151. /// <summary>
  152. /// GetIpNetTable external method
  153. /// </summary>
  154. /// <param name="pIpNetTable"></param>
  155. /// <param name="pdwSize"></param>
  156. /// <param name="bOrder"></param>
  157. /// <returns></returns>
  158. [ DllImport("IpHlpApi.dll")]
  159. [ return: MarshalAs(UnmanagedType.U4)]
  160. static extern int GetIpNetTable(IntPtr pIpNetTable,
  161. [MarshalAs(UnmanagedType.U4)] ref int pdwSize, bool bOrder);
  162. /// <summary>
  163. /// Error codes GetIpNetTable returns that we recognise
  164. /// </summary>
  165. const int ERROR_INSUFFICIENT_BUFFER = 122;
  166. /// <summary>
  167. /// Get the IP and MAC addresses of all known devices on the LAN
  168. /// </summary>
  169. /// <remarks>
  170. /// 1) This table is not updated often - it can take some human-scale time
  171. /// to notice that a device has dropped off the network, or a new device
  172. /// has connected.
  173. /// 2) This discards non-local devices if they are found - these are multicast
  174. /// and can be discarded by IP address range.
  175. /// </remarks>
  176. /// <returns></returns>
  177. private static Dictionary<IPAddress, PhysicalAddress> GetAllDevicesOnLAN()
  178. {
  179. Dictionary<IPAddress, PhysicalAddress> all = new Dictionary<IPAddress, PhysicalAddress>();
  180. // Add this PC to the list...
  181. all.Add(GetIPAddress(), GetMacAddress());
  182. int spaceForNetTable = 0;
  183. // Get the space needed
  184. // We do that by requesting the table, but not giving any space at all.
  185. // The return value will tell us how much we actually need.
  186. GetIpNetTable(IntPtr.Zero, ref spaceForNetTable, false);
  187. // Allocate the space
  188. // We use a try-finally block to ensure release.
  189. IntPtr rawTable = IntPtr.Zero;
  190. try
  191. {
  192. rawTable = Marshal.AllocCoTaskMem(spaceForNetTable);
  193. // Get the actual data
  194. int errorCode = GetIpNetTable(rawTable, ref spaceForNetTable, false);
  195. if (errorCode != 0)
  196. {
  197. // Failed for some reason - can do no more here.
  198. throw new Exception( string.Format(
  199. "Unable to retrieve network table. Error code {0}", errorCode));
  200. }
  201. // Get the rows count
  202. int rowsCount = Marshal.ReadInt32(rawTable);
  203. IntPtr currentBuffer = new IntPtr(rawTable.ToInt64() + Marshal.SizeOf( typeof(Int32)));
  204. // Convert the raw table to individual entries
  205. MIB_IPNETROW[] rows = new MIB_IPNETROW[rowsCount];
  206. for ( int index = 0; index < rowsCount; index++)
  207. {
  208. rows[index] = (MIB_IPNETROW)Marshal.PtrToStructure( new IntPtr(currentBuffer.ToInt64() +
  209. (index * Marshal.SizeOf( typeof(MIB_IPNETROW)))
  210. ),
  211. typeof(MIB_IPNETROW));
  212. }
  213. // Define the dummy entries list (we can discard these)
  214. PhysicalAddress virtualMAC = new PhysicalAddress( new byte[] { 0, 0, 0, 0, 0, 0 });
  215. PhysicalAddress broadcastMAC = new PhysicalAddress( new byte[] { 255, 255, 255, 255, 255, 255 });
  216. foreach (MIB_IPNETROW row in rows)
  217. {
  218. IPAddress ip = new IPAddress(BitConverter.GetBytes(row.dwAddr));
  219. byte[] rawMAC = new byte[] { row.mac0, row.mac1, row.mac2, row.mac3, row.mac4, row.mac5 };
  220. PhysicalAddress pa = new PhysicalAddress(rawMAC);
  221. if (!pa.Equals(virtualMAC) && !pa.Equals(broadcastMAC) && !IsMulticast(ip))
  222. {
  223. //Console.WriteLine("IP: {0}\t\tMAC: {1}", ip.ToString(), pa.ToString());
  224. if (!all.ContainsKey(ip))
  225. {
  226. all.Add(ip, pa);
  227. }
  228. }
  229. }
  230. }
  231. finally
  232. {
  233. // Release the memory.
  234. Marshal.FreeCoTaskMem(rawTable);
  235. }
  236. return all;
  237. }
  238. /// <summary>
  239. /// Gets the IP address of the current PC
  240. /// </summary>
  241. /// <returns></returns>
  242. private static IPAddress GetIPAddress()
  243. {
  244. String strHostName = Dns.GetHostName();
  245. IPHostEntry ipEntry = Dns.GetHostEntry(strHostName);
  246. IPAddress[] addr = ipEntry.AddressList;
  247. foreach (IPAddress ip in addr)
  248. {
  249. if (!ip.IsIPv6LinkLocal)
  250. {
  251. return (ip);
  252. }
  253. }
  254. return addr.Length > 0 ? addr[ 0] : null;
  255. }
  256. /// <summary>
  257. /// Gets the MAC address of the current PC.
  258. /// </summary>
  259. /// <returns></returns>
  260. private static PhysicalAddress GetMacAddress()
  261. {
  262. foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
  263. {
  264. // Only consider Ethernet network interfaces
  265. if (nic.NetworkInterfaceType == NetworkInterfaceType.Ethernet &&
  266. nic.OperationalStatus == OperationalStatus.Up)
  267. {
  268. return nic.GetPhysicalAddress();
  269. }
  270. }
  271. return null;
  272. }
  273. /// <summary>
  274. /// Returns true if the specified IP address is a multicast address
  275. /// </summary>
  276. /// <param name="ip"></param>
  277. /// <returns></returns>
  278. private static bool IsMulticast(IPAddress ip)
  279. {
  280. bool result = true;
  281. if (!ip.IsIPv6Multicast)
  282. {
  283. byte highIP = ip.GetAddressBytes()[ 0];
  284. if (highIP < 224 || highIP > 239)
  285. {
  286. result = false;
  287. }
  288. }
  289. return result;
  290. }
  291. #endregion
  292. #region MAC扫描方法2
  293. static List< string> ips = new List< string>();
  294. static Dictionary< string, string> dic1 = new Dictionary< string, string>();
  295. static void GetIPAddress2()
  296. {
  297. string myHostName = Dns.GetHostName(); //本机名
  298. string myHostIP = Dns.GetHostEntry(myHostName).AddressList[ 1].ToString(); //本机IP地址
  299. string IpRange = myHostIP.Remove(myHostIP.LastIndexOf( '.')); //IP网段
  300. for ( int r = 1; r <= 255; r++) //枚举网段计算机
  301. {
  302. Ping ping = new Ping();
  303. ping.PingCompleted += new PingCompletedEventHandler(ping_Completed); //事件绑定方法
  304. string pingIP = IpRange + "." + r.ToString();
  305. ping.SendAsync(pingIP, 1000, null);
  306. }
  307. }
  308. static void ping_Completed(object sender, PingCompletedEventArgs e)
  309. {
  310. if (e.Reply.Status == IPStatus.Success)
  311. {
  312. ips.Add(e.Reply.Address.ToString());
  313. if (!dic1.ContainsKey(e.Reply.Address.ToString()))
  314. {
  315. dic1[e.Reply.Address.ToString()] = "";
  316. }
  317. }
  318. }
  319. #endregion
  320. private void Msg(string e)
  321. {
  322. try
  323. {
  324. string msg = "";
  325. //if (string.IsNullOrEmpty(richTextBox1.Text))
  326. //{
  327. // msg = e;
  328. //}
  329. //else
  330. //{
  331. // msg = richTextBox1.Text + "\r\n" + e;
  332. //}
  333. msg = e;
  334. if ( base.InvokeRequired)
  335. {
  336. base.Invoke( new MethodInvoker(() =>
  337. {
  338. richTextBox1.Text = richTextBox1.Text + "\r\n" + e;
  339. }));
  340. }
  341. else
  342. {
  343. richTextBox1.Text = richTextBox1.Text + "\r\n" + e;
  344. }
  345. }
  346. catch
  347. {
  348. }
  349. }
  350. }
  351. }

四、 外网远程唤醒方案

  1. 家中放一台微型迷你低功耗计算机或者网关(树莓派、网关、迷你服务器)功耗在10W左右,保持24小时常开,一年电费在一百左右。安装向日葵或者ToDesk设置无人值守,支持电脑和手机App连接。随时随地连接到桌面后,用远程发包软件(文中源码或直接下载打包程序)来远程网络唤醒局域网内其他电脑。
  2. 使用向日葵开机棒,参照官方设置即可,主要是开机棒开放了mac地址开机。可以使得开机棒不局限于一台计算机开机了。在向日葵的网站上找到开机棒,或者在手机就app中找到,然后输入mac地址,即可。
  3. 使用路由器(例如TP-Link)自带的域名解析功能,参考文章:【超详细】Windows设置远程唤醒WOL+远程连接(远程开机)_wyouzhi@yyds的博客-CSDN博客_远程开机与远程唤醒bios设置

转载:https://blog.csdn.net/hwt0101/article/details/127401108
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场