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地址是小写的,或者先后次序颠倒的,本身转换为正常的便可。
|