獲取網卡的MAC地址的方法很多,如:Netbios,SNMP,GetAdaptersInfo等。經過測試發現 Netbios 方法在網線拔出的情況下獲取不到MAC,而 SNMP 方法有時會獲取多個重復的網卡的MAC,試來試去還是 GetAdaptersInfo 方法比較好,網線拔出的情況下可以獲取MAC,而且很准確,不會重復獲取網卡。
GetAdaptersInfo 方法也不是十全十美,也存在些問題:
1)如何區分物理網卡和虛擬網卡;
2)如何區分無線網卡和有線網卡;
3)“禁用”的網卡獲取不到。
關於問題1和問題2我的處理辦法是:
區分物理網卡和虛擬網卡:pAdapter->Description中包含"PCI"是:物理網卡。(試了3台機器可以)
區分無線網卡和有線網卡:pAdapter->Type為71的是:無線網卡。(試了2個無線網卡也可以)
現在把代碼貼出來和大家分享:
#include "stdafx.h"
#include <atlbase.h>
#include <atlconv.h>
#include "iphlpapi.h"
#pragma comment ( lib, "Iphlpapi.lib" )
int main(int argc, char* argv[])
{
PIP_ADAPTER_INFO pAdapterInfo;
PIP_ADAPTER_INFO pAdapter = NULL;
DWORD dwRetVal = 0;
pAdapterInfo = (IP_ADAPTER_INFO *) malloc( sizeof(IP_ADAPTER_INFO) );
ULONG ulOutBufLen = sizeof(IP_ADAPTER_INFO);
if (GetAdaptersInfo( pAdapterInfo, &ulOutBufLen) != ERROR_SUCCESS)
{
GlobalFree (pAdapterInfo);
pAdapterInfo = (IP_ADAPTER_INFO *) malloc (ulOutBufLen);
}
if ((dwRetVal = GetAdaptersInfo( pAdapterInfo, &ulOutBufLen)) == NO_ERROR)
{
pAdapter = pAdapterInfo;
while (pAdapter)
{
if(
strstr(pAdapter->Description,"PCI") > 0 // pAdapter->Description中包含"PCI"為:物理網卡
|| pAdapter->Type == 71 // pAdapter->Type是71為:無線網卡
)
{
printf("------------------------------------------------------------\n");
printf("Adapter Name: \t%s\n", pAdapter->AdapterName);
printf("Adapter Desc: \t%s\n", pAdapter->Description);
printf("Adapter Addr: \t");
for (UINT i = 0; i < pAdapter->AddressLength; i++)
{
printf("%02X%c", pAdapter->Address[i],
i == pAdapter->AddressLength - 1 ? '\n' : '-');
}
printf("Adapter Type: \t%d\n", pAdapter->Type);
printf("IP Address: \t%s\n", pAdapter->IpAddressList.IpAddress.String);
printf("IP Mask: \t%s\n", pAdapter->IpAddressList.IpMask.String);
}
pAdapter = pAdapter->Next;
}
}
else
{
printf("Call to GetAdaptersInfo failed.\n");
}
return 0;
}