获取网卡mac地址,区分虚拟机网卡

 

BOOL IsLocalAdapter( const char *pAdapterName )
{
BOOL ret_value = FALSE;
char szDataBuf[MAX_PATH+1] = {0};
DWORD dwDataLen = MAX_PATH;
DWORD dwType = REG_SZ;
HKEY hLocalNet = NULL;


#define NET_CARD_KEY (_T("System\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}"))
sprintf(szDataBuf, "%s\\%s\\Connection",NET_CARD_KEY, pAdapterName);


if(ERROR_SUCCESS != RegOpenKeyEx(HKEY_LOCAL_MACHINE ,szDataBuf ,0 ,KEY_READ, &hLocalNet))
{
return FALSE;
}


/*注册表中网卡信息有的没有该项
if (ERROR_SUCCESS != RegQueryValueEx(hLocalNet, _T("MediaSubType"), 0, &dwType, (BYTE *)szDataBuf, &dwDataLen))
{
goto ret;
}
if (*((DWORD *)szDataBuf)!=0x01)
goto ret;
*/
dwDataLen = MAX_PATH;
memset(szDataBuf,0,sizeof(szDataBuf));
if (ERROR_SUCCESS != RegQueryValueEx(hLocalNet, _T("PnpInstanceID"), 0, &dwType, (BYTE *)szDataBuf, &dwDataLen))
{
goto ret;
}


if (strncmp(szDataBuf, "PCI", strlen("PCI")))
{
//注册表中网卡信息中该项值中的"PCI"并不都位于最前
CString id = szDataBuf;
int ret = id.Find("PCI");
if ( ret == -1 )
{
goto ret;
}
}


ret_value = TRUE;


ret:
RegCloseKey(hLocalNet);


return ret_value;
}


void MacAddressToString(const LPBYTE Address, LPSTR lpsz, int nAddressLength = 6)
{
 LPSTR p = lpsz;
 for ( int i = 0; i < nAddressLength ; i++ )
 {
  p += sprintf( p, i ? ":%02x" : "%02x", Address[i]);
 }
}

 

#if 1
#include"stdafx.h"
#include
#include
#include"iphlpapi.h"
#pragma comment(lib,"Iphlpapi.lib")
int GetMacByCmd( char* mac )
{
 PIP_ADAPTER_INFO pAdapterInfo;
 DWORD AdapterInfoSize = 0;
 DWORD dwRetVal=0;

 GetAdaptersInfo(NULL,&AdapterInfoSize);
 pAdapterInfo = ( PIP_ADAPTER_INFO )GlobalAlloc(GPTR,AdapterInfoSize);

 GetAdaptersInfo(pAdapterInfo,&AdapterInfoSize);

 PIP_ADAPTER_INFO pAdapter = pAdapterInfo;

 while(pAdapter)
 {
  if ( IsLocalAdapter(pAdapter->AdapterName) )
  {
   MacAddressToString(pAdapter->Address,mac,pAdapter->AddressLength);
   break;
  }
  else
  {
   pAdapter = pAdapter->Next;
  }
 }
 GlobalFree(pAdapterInfo);
 return 0;
}
#endif

你可能感兴趣的:(知识百科,虚拟机,path,null,byte,network)