Unity網絡通訊(一)獲取計算機的MAC地址


 

 1   string GetMac()
 2    {
 3         string mac = "";
 4         mac = GetMacAddressBySendARP();
 5         return mac;
 6     }
 7     [DllImport("Iphlpapi.dll")]
 8     static extern int SendARP(Int32 DestIP, Int32 SrcIP, ref Int64 MacAddr, ref Int32 PhyAddrLen);
 9     /// <summary>  
10     /// SendArp獲取MAC地址  
11     /// </summary>  
12     /// <returns></returns>  
13     public string GetMacAddressBySendARP()
14     {
15         StringBuilder strReturn = new StringBuilder();
16         try
17         {
18             System.Net.IPHostEntry Tempaddr = (System.Net.IPHostEntry)Dns.GetHostByName(Dns.GetHostName());
19             System.Net.IPAddress[] TempAd = Tempaddr.AddressList;
20             Int32 remote = (int)TempAd[0].Address;
21             Int64 macinfo = new Int64();
22             Int32 length = 6;
23             SendARP(remote, 0, ref macinfo, ref length);
24             string temp = System.Convert.ToString(macinfo, 16).PadLeft(12, '0').ToUpper();
25             int x = 12;
26             for (int i = 0; i < 6; i++)
27             {
28                 if (i == 5) { strReturn.Append(temp.Substring(x - 2, 2)); }
29                 else { strReturn.Append(temp.Substring(x - 2, 2) + ":"); }
30                 x -= 2;
31             }
32             return strReturn.ToString();
33         }
34         catch
35         {
36             return "";
37         }
38     }  

以上代碼可直接調用GetMac()函數獲取電腦的Mac地址


免責聲明!

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



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