最近用winpcap编程发现winpcap不能直接的提取本地网卡的mac地址.
于是通过向自己发arp请求来获得本地的mac.自己写了段代码,如下:
int
getmmac()
{
unsigned
char
sendbuf[
42
];
int
i
=
7
,k;
ETHDR eth;
ARPHDR arp;
struct
pcap_pkthdr
*
pkt_header;
u_char
*
pkt_data;
for
(k
=
0
;k
<
6
;k
++
)
{
eth.eh_dst[k]
=
0xff
;
eth.eh_src[k]
=
0x0f
;
arp.arp_sha[k]
=
0x0f
;
arp.arp_tha[k]
=
0x00
;
}
eth.eh_type
=
htons(ETH_ARP);
arp.arp_hdr
=
htons(ARP_HARDWARE);
arp.arp_pro
=
htons(ETH_IP);
arp.arp_hln
=
6
;
arp.arp_pln
=
4
;
arp.arp_opt
=
htons(ARP_REQUEST);
arp.arp_tpa
=
myip
->
ip;
arp.arp_spa
=
inet_addr(
"
127.0.0.2
"
);
memset(sendbuf,
0
,
sizeof
(sendbuf));
memcpy(sendbuf,
&
eth,
sizeof
(eth));
memcpy(sendbuf
+
sizeof
(eth),
&
arp,
sizeof
(arp));
if
(pcap_sendpacket(slecadopt,sendbuf,
42
)
==
0
)
{
printf(
"
PacketSend succeed\n\n
"
);
}
else
{
printf(
"
PacketSendPacket in getmine Error: %d\n
"
,GetLastError());
return
0
;
}
while
((k
=
pcap_next_ex(slecadopt,
&
pkt_header,(
const
u_char
**
)
&
pkt_data))
>=
0
)
{
if
(
*
(unsigned
short
*
)(pkt_data
+
12
)
==
htons(ETH_ARP)
&&*
(unsigned
short
*
)(pkt_data
+
20
)
==
htons(ARP_REPLY)
&&*
(unsigned
long
*
)(pkt_data
+
38
)
==
inet_addr(
"
127.0.0.2
"
))
{
for
(i
=
0
;i
<
6
;i
++
)
{
myip
->
mac[i]
=*
(unsigned
char
*
)(pkt_data
+
22
+
i);
}
break
;
}
}
if
(i
==
6
)
{
return
1
;
}
else
{
return
0
;
}
}
写的是一个函数,其中arp请求的发送方地址填的是127.0.0.2.这个都没什么关系.
当然提取本地的mac还可以用api直接获取.但是不知道用pcap还有别的好方法.高手指教.谢谢