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地址

posted @ 2016-05-26 17:37  孙小超  阅读(2485)  评论(0编辑  收藏  举报