最近在一直都在研究PC機硬件和軟件相結合的軟件,硬件信息都是通過C++與驅動結合獲取。對於一個好久都沒有接觸C++的人來說看這些東西太費勁了,必須的重新撿一下C++的基礎知識,必然也少不了C知識,底層都是通過C++與C結合,提供接口給J2EE調用,J2EE也忘的一干二凈了。從C++那也了解到了AMT、ACPI、DPM等不少驅動的結合,可以取到哪些硬件信息和對硬件操作,有空就使用C#做了Demo,不過還是使用C#比較得心應手。
這次是試驗了一下網卡的Wake On Lan功能,就是能夠在廣域網和局域網能遠程啟動目標機器,需要網卡支持Wake on Lan功能,關閉機器后網卡的燈會一直亮着,還需要檢查以下2點設置。
1. 進入BIOS設置,Power->Automatic Power On里面,設置Wake on LAN = Enable/Automatic,不同機器的BIOS設置位置不同,找到對應的Wake on LAN選項設置就OK。
2. 進入網卡設置,我的電腦->右鍵”管理“->設備管理器->網絡適配器,找到對應的網卡右鍵”屬性“->電源管理,勾選允許此設備喚醒計算機和子選項(只允許幻數據包喚醒計算機),”高級“選項卡里面,檢查屬性里的喚醒幻數據包=已啟用 and 喚醒模式匹配=已啟用。
注:不同的網卡設置可能會不一樣
下面就用代碼詳細說明實現方式:
#region WOL遠程喚醒機器 /// <summary> /// 通過WOL遠程喚醒機器方法 /// 摘要:喚醒方法為網卡提供的魔術封包功能,即以廣播模式發送6個FF加上16遍目標機器MAC地址的字節數組 /// </summary> /// <param name="mac">要喚醒機器的MAC</param> /// <param name="ip">要喚醒機器的子網掩碼</param> /// <param name="port">UDP消息發送端口</param> private static void WakeOnLan(string mac,string ip, int port) { IPEndPoint point; UdpClient client = new UdpClient(); byte[] magicBytes = GetMagicPacket(mac); point = new IPEndPoint(IPAddress.Parse(ip), port);//廣播模式:255.255.255.255 try { int result = client.Send(magicBytes, magicBytes.Length, point); } catch (SocketException ex) { throw new Exception(ex.ToString()); } } /// <summary> /// 拼裝MAC魔術封包 /// </summary> /// <param name="hexString">MAC地址字符串</param> /// <returns></returns> public static byte[] GetMagicPacket(string macString) { byte[] returnBytes = new byte[102]; string commandString = "FFFFFFFFFFFF"; for (int i = 0; i < 6; i++) returnBytes[i] = Convert.ToByte(commandString.Substring(i * 2, 2), 16); byte[] macBytes = StrToHexByte(macString); for (int i = 6; i < 102; i++) { returnBytes[i] = macBytes[i % 6]; } return returnBytes; } /// <summary> /// MAC地址字符串轉16進制字節數組 /// </summary> /// <param name="hexString">MAC地址字符串</param> /// <returns></returns> public static byte[] StrToHexByte(string hexString) { hexString = hexString.Replace("-", ""); if ((hexString.Length % 2) != 0) hexString += " "; byte[] returnBytes = new byte[hexString.Length / 2]; for (int i = 0; i < returnBytes.Length; i++) returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16); return returnBytes; } #endregion
調用主函數:
static void Main(string[] args) { string macAddress, ipAddress; int port; Console.Write("Please input MAC:"); macAddress = Console.ReadLine(); if (string.IsNullOrEmpty(macAddress)) { macAddress = "F8-0F-41-21-12-68"; Console.WriteLine("Default MAC:" + macAddress); } Console.Write("Please input Subnet:"); ipAddress = Console.ReadLine(); if (string.IsNullOrEmpty(ipAddress)) { ipAddress = "255.255.255.255"; Console.WriteLine("Default Subnet:" + ipAddress); } Console.Write("Please input Port:"); if (!string.IsNullOrEmpty(Console.ReadLine())) { port = int.Parse(Console.ReadLine()); } else { port = 9000; Console.WriteLine("Default Port:" + port); } WakeOnLan(macAddress, ipAddress, port); Console.Read(); }
這個實例就介紹到這里吧,歡迎大家來拍磚!如有其它好的方法希望不要吝嗇,拿出來分享給大家一塊學習進步!