ARP(Address Resolution Protocol) 即 地址解析協議,是根據IP地址獲取物理地址的一個TCP/IP協議。
SendARP(Int32 dest, Int32 host, out Int64 mac, out Int32 length)
①dest:訪問的目標IP地址,既然獲取本機網卡地址,寫本機IP即可 這個地址比較特殊,必須從十進制點分地址轉換成32位有符號整數 在C#中為Int32;
②host:源IP地址,即時發送者的IP地址,這里可以隨便填寫,填寫Int32整數即可;
③mac:返回的目標MAC地址(十進制),我們將其轉換成16進制后即是想要的結果用out參數加以接收;
④length:返回的是pMacAddr目標MAC地址(十進制)的長度,用out參數加以接收。
如果使用的是C++或者C語言可以直接調用 inet_addr("192.168.0.×××")得到 參數dest 是關鍵
現在用C#來獲取,首先需要導入"ws2_32.dll"這個庫,這個庫中存在inet_addr(string cp)這個方法,之后我們就可以調用它了。
//首先,要引入命名空間:using System.Runtime.InteropServices;
1 using System.Runtime.InteropServices;
//接下來導入C:\Windows\System32下的"ws2_32.dll"動態鏈接庫,先去文件夾中搜索一下,文件夾中沒有Iphlpapi.dll的在下面下載
2 [DllImport("ws2_32.dll")]
3 private static extern int inet_addr(string ip);//聲明方法
Iphlpapi.dll的點擊 這里 下載
//第二 調用方法
Int32 desc = inet_addr("192.168.0.××");
/*由於個別WinCE設備是不支持"ws2_32.dll"動態庫的,所以我們需要自己實現inet_addr()方法
輸入是點分的IP地址格式(如A.B.C.D)的字符串,從該字符串中提取出每一部分,為int,假設得到4個int型的A,B,C,D,
,IP = D<<24 + C<<16 + B<<8 + A(網絡字節序),即inet_addr(string ip)的返回結果,
我們也可以把該IP轉換為主機字節序的結果,轉換方法一樣 A<<24 + B<<16 + C<<8 + D
*/
接下來是完整代碼
using System;
using System.Runtime.InteropServices;
using System.Net;
using System.Diagnostics;
using System.Net.Sockets;
public class MacAddressDevice
{
[DllImport("Iphlpapi.dll")]
private static extern int SendARP(Int32 dest, Int32 host, ref Int64 mac, ref Int32 length);
//獲取本機的IP
public static byte[] GetLocalIP()
{
//得到本機的主機名
string strHostName = Dns.GetHostName();
try
{
//取得本機所有IP(IPV4 IPV6 ...)
IPAddress[] ipAddress = Dns.GetHostEntry(strHostName).AddressList;
byte[] host = null;
foreach (var ip in ipAddress)
{
while (ip.GetAddressBytes().Length == 4)
{
host = ip.GetAddressBytes();
break;
}
if (host != null)
break;
}
return host;
}
catch (Exception)
{
return null;
}
}
// 獲取本地主機MAC地址
public static string GetLocalMac(byte[] ip)
{
if(ip == null)
return null;
int host = (int)((ip[0]) + (ip[1] << 8) + (ip[2] << 16) + (ip[3] << 24));
try
{
Int64 macInfo = 0;
Int32 len = 0;
int res = SendARP(host, 0, out macInfo, out len);
return Convert.ToString(macInfo, 16);
}
catch (Exception err)
{
Console.WriteLine("Error:{0}", err.Message);
}
return null;
}
}
}
最終取得Mac地址
//本機Mac地址 string Mac = GetLocalMac(GetLocalIP()); //得到Mac地址是小寫的,或者前后次序顛倒的,自己轉換為正常的即可。
