C#獲取本機和其它計算機物理網卡地址(MAC)


2011-04-18 23:39:45|170次閱讀|上傳:huigezrx【已有0條評論】發表評論

關鍵詞:C# , Windows編程|來源:VC編程網

驗證計算機MAC地址進行軟件授權是一種通用的方法,C#可以輕松獲取計算機的MAC地址,本文采用實際的源代碼講述了兩種獲取網卡的方式,第一種 方法使用ManagementClass類,只能獲取本機的計算機網卡物理地址,第二種方法使用Iphlpapi.dll的SendARP方法,可以獲取 本機和其它計算機的MAC地址。

    方法1:使用ManagementClass類

          示例:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/// <summary>
/// 獲取網卡物理地址
/// </summary>
/// <returns></returns>
public static string getMacAddr_Local()
{
     string madAddr = null ;
     ManagementClass mc = new ManagementClass( "Win32_NetworkAdapterConfiguration" );
     ManagementObjectCollection moc2 = mc.GetInstances();
     foreach (ManagementObject mo in moc2)
     {
         if (Convert.ToBoolean(mo[ "IPEnabled" ]) == true )
         {
             madAddr = mo[ "MacAddress" ].ToString();
             madAddr = madAddr.Replace( ':' , '-' );
         }
         mo.Dispose();
     }
     return madAddr;
}
說明:

   1.需要給項目增加引用:System.Management,如圖:

    2.在程序開始添加包引入語句:using System.Management;

    3.本方案只能獲取本機的MAC地址;

    方法2:使用SendARP類

          示例:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
//下面一種方法可以獲取遠程的MAC地址
[DllImport( "Iphlpapi.dll" )]
static extern int SendARP(Int32 DestIP, Int32 SrcIP, ref Int64 MacAddr, ref Int32 PhyAddrLen);
[DllImport( "Ws2_32.dll" )]
static extern Int32 inet_addr( string ipaddr);        
/// <summary>
/// SendArp獲取MAC地址
/// </summary>
/// <param name="RemoteIP">目標機器的IP地址如(192.168.1.1)</param>
/// <returns>目標機器的mac 地址</returns>
public static string getMacAddr_Remote( string RemoteIP)
{
     StringBuilder macAddress = new StringBuilder();
     try
     {
         Int32 remote = inet_addr(RemoteIP);
         Int64 macInfo = new Int64();
         Int32 length = 6;
         SendARP(remote, 0, ref macInfo, ref length);
         string temp = Convert.ToString(macInfo, 16).PadLeft(12, '0' ).ToUpper();
         int x = 12;
         for ( int i = 0; i < 6; i++)
         {
             if (i == 5)
             {
                 macAddress.Append(temp.Substring(x - 2, 2));
             }
             else
             {
                 macAddress.Append(temp.Substring(x - 2, 2) + "-" );
             }
             x -= 2;
         }
         return macAddress.ToString();
     }
     catch
     {
         return macAddress.ToString();
     }
}
說明:

    1.在程序開始添加包引入語句:using System.Runtime.InteropServices;

    2.該方法可以獲取遠程計算機的MAC地址;


免責聲明!

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



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