编译环境VS2008,UNICODE编码
#include <atlconv.h>
BYTE m_MAC[10][6]; //the mac address of this computer, 10 NICs
int m_nMAC;
void CGetAdapterMacDlg::GetMac()
{
PIP_ADAPTER_INFO pAdapterInfo;
PIP_ADAPTER_INFO pAdapter=NULL;
DWORD dwRetVal=0;
USES_CONVERSION;
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( isLocalNetCard( A2T(pAdapter->AdapterName) ) )
{
for(UINT i=0;i<pAdapter->AddressLength;i++)
{
//存储匹配的Mac地址
if(pAdapter->AddressLength == 6)
m_MAC[m_nMAC][i] = pAdapter->Address[i];
}
++m_nMAC;
}
pAdapter=pAdapter->Next;
}
}
}
bool CGetAdapterMacDlg::isLocalNetCard(TCHAR * AdapterName)
{
HKEY hKey,hSubKey,hNdiKey,hNdiIntKey;
//打开注册表
if(RegOpenKeyEx(HKEY_LOCAL_MACHINE,_T("System\\CurrentControlSet\\Control\\Class\\{4d36e972-e325-11ce-bfc1-08002be10318}"),\
0,KEY_READ,&hKey)!=ERROR_SUCCESS)
return FALSE;
DWORD dwIndex = 0;
DWORD dwBufSize = 256;
DWORD dwDataType;
TCHAR szSubKey[256]={0};
TCHAR szData[256]={0};
//查找物理网卡信息
while(RegEnumKeyEx(hKey,dwIndex++,szSubKey,&dwBufSize,NULL,NULL,NULL,NULL)==ERROR_SUCCESS)
{
if(RegOpenKeyEx(hKey,szSubKey,0,KEY_READ,&hSubKey)==ERROR_SUCCESS)
{
int find=0;
if(RegOpenKeyEx(hSubKey,_T("Ndi"),0,KEY_READ,&hNdiKey)==ERROR_SUCCESS)
{
dwBufSize=256;
if(RegQueryValueEx(hNdiKey, _T("Service"),0,&dwDataType,(LPBYTE)szData,&dwBufSize)==ERROR_SUCCESS)
{
//判断虚拟网卡
if(_tcscmp( szData,_T("VMnetAdapter")) == 0)
break;
else if(RegOpenKeyEx(hSubKey,_T("Ndi\\Interfaces"),0,KEY_READ,&hNdiIntKey)==ERROR_SUCCESS)
{
dwBufSize=256;
if(RegQueryValueEx(hNdiIntKey,_T("LowerRange"),0,&dwDataType,(LPBYTE)szData,&dwBufSize) ==ERROR_SUCCESS)
{
//判断是不是以太网卡
if(_tcscmp( _T("ethernet"),szData) == 0)
{
find=1;
}//判断是不是无线网卡
else if(Stringcmp( _T("ethernet"), szData) == TRUE)
find=1;
}
RegCloseKey(hNdiIntKey);
}
RegCloseKey(hNdiKey);
}
if(find)
{
dwBufSize=256;
if(RegQueryValueEx(hSubKey, _T("NetCfgInstanceID"), 0, &dwDataType, (LPBYTE)szData, &dwBufSize) == ERROR_SUCCESS)
{
if(_tcscmp(AdapterName, szData) == 0)
{
//cout<< szData <<endl;
RegCloseKey(hSubKey);
RegCloseKey(hKey);
return true;
}
}
}
RegCloseKey(hSubKey);
}
}
dwBufSize = 256;
}
RegCloseKey(hKey);
return false;
}
//////////////////////////////////////////////////////////
//如果des中有一子串和base相同,则返回true,否则返回false
//////////////////////////////////////////////////////////
bool CGetAdapterMacDlg::Stringcmp(TCHAR *base,TCHAR *des)
{
int baselen=_tcslen (base);
int deslen=_tcslen (des);
TCHAR temp[9] = {0};
int i = 0;
int flag = 0;
memset( temp, 0, _tcslen(temp) );
for( i=0; i<=( deslen-baselen ); i++ )
{
_tcsncpy( temp, des+i, baselen );
if( _tcscmp(base, temp) == 0 )
{
flag = 1;
break;
}
}
if( flag )
return TRUE;
else
return FALSE;
}