網卡喚醒電腦


  進入BIOS一般會發現有網卡喚醒、PCI調制解調器喚醒、串口Ring喚醒和時鍾喚醒。一般用戶的定時開機需求由時鍾喚醒即可解決,不過若是想要在外地也可以輕松打開自己的電腦,網卡喚醒可以解決這個問題。

  網卡喚醒只需要兩個參數:廣播地址和MAC地址。如果是內網網卡喚醒則只需要MAC地址,廣播地址是255.255.255.255。但是怎么知道外網ip的廣播地址呢,廣播地址等於子網按位求反和IP地址的或運算。

public static string GetBroadcast(IPAddress ipAddress, IPAddress subnetMask)
        {
            byte[] ip = ipAddress.GetAddressBytes();
            byte[] sub = subnetMask.GetAddressBytes();

            for (int i = 0; i < ip.Length; i++)
            {
                ip[i] = (byte) ((~sub[i]) | ip[i]); //廣播地址=子網按位求反 或 IP地址
            }

            return new IPAddress(ip).ToString();
        }
View Code

  至此就只需要知道發什么給需要被喚醒的電腦了,MAC魔術封包可以實現網卡喚醒

/// <summary>
        ///     字符串轉16進制字節數組
        /// </summary>
        /// <param name="hexStr"></param>
        /// <returns></returns>
        public static byte[] StrToHexByte(string hexStr)
        {
            hexStr = hexStr.Replace(" ", "").Replace("-", "").Replace(":", "");
            if ((hexStr.Length%2) != 0)
                hexStr += " ";
            byte[] returnBytes = new byte[hexStr.Length/2];
            for (int i = 0; i < returnBytes.Length; i++)
                returnBytes[i] = Convert.ToByte(hexStr.Substring(i*2, 2), 16);
            return returnBytes;
        }

        /// <summary>
        ///     拼裝MAC魔術封包
        /// </summary>
        /// <param name="macStr"></param>
        /// <returns></returns>
        public static byte[] GetMagicPacket(string macStr)
        {
            byte[] returnBytes = new byte[102];
            const string commandStr = "FFFFFFFFFFFF";
            for (int i = 0; i < 6; i++)
                returnBytes[i] = Convert.ToByte(commandStr.Substring(i*2, 2), 16);
            byte[] macBytes = StrToHexByte(macStr);
            for (int i = 6; i < 102; i++)
            {
                returnBytes[i] = macBytes[i%6];
            }
            return returnBytes;
        }
View Code

  另外附上IP轉MAC的方法,不過需要在該電腦開啟的情況下才能獲取它的MAC地址。

  此網卡喚醒做了一個Winform界面的程序,一個控制台的程序,控制台程序由bat文件批量喚醒電腦

@echo off
start D:\NetworkCardWake.exe 00-E0-4C-68-08-E7 183.233.129.53 183.233.129.1
View Code

  本程序有參考其他人的博客,完整程序


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM