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)這個方法,以後咱們就能夠調用它了。
1
2
3
4
5
|
//首先,要引入命名空間: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的點擊 這裏 下載
1
|
|
1
2
3
4
5
6
7
8
9
10
|
//第二 調用方法
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
*/
|
接下來是完整代碼
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
|
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地址
1
2
3
4
|
//本機Mac地址
string
Mac = GetLocalMac(GetLocalIP());
//獲得Mac地址是小寫的,或者先後次序顛倒的,本身轉換爲正常的便可。
|