由于终端设备多网卡使用的问题,以前使用Netbios()获取网卡MAC地址的方法可能导致不可靠的问题。
现推荐大家使用如下方法实现:
CString GetLicense(CString strMac)
{
int P1=0, P2=0, P3=0, P4=0, P5=0, P6=0;
sscanf(strMac, "% 02X% 02X% 02X% 02X% 02X% 02X", &P1, &P2, &P3, &P4, &P5, &P6);
int nTemp = P1+P2+P3+P4+P5+P6;
CString strAdd;
strAdd.Format("% 02X% 02X", nTemp/6, nTemp%0xFF);
return strMac+strAdd;
}
CString GetMacByName(CString strName)
{
CString strName2=strName+":";
char szFile[512], szCmd[512];
memset(szFile, 0x00, sizeof(szFile));
if(!GetSystemDirectory(szFile, sizeof(szFile)))
{
strcpy(szFile, "C:");
}
strcat(szFile, "\\ip.txt");
strcpy(szCmd, "/c ipconfig /all >");
strcat(szCmd, szFile);
SHELLEXECUTEINFO ShExecInfo = {0};
ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
ShExecInfo.lpFile = "cmd.exe";
ShExecInfo.lpParameters = szCmd;
ShExecInfo.nShow = SW_HIDE;
ShellExecuteEx(&ShExecInfo);
WaitForSingleObject(ShExecInfo.hProcess,INFINITE);
// ShellExecute(NULL, "open", "cmd.exe", szCmd, NULL, SW_HIDE);
FILE* fp = fopen(szFile, "r");
if(!fp) return "";
fseek(fp, 0, SEEK_END);
int len = ftell(fp);
char* pData=(char*)malloc(len+1);
memset(pData, 0x00, len+1);
fseek(fp, 0, SEEK_SET);
fread(pData, 1, len, fp);
fclose(fp);
char* pPos=strstr(pData, strName2.GetBuffer(0));
if(pPos)
{
char* pPos2=strstr(pPos, "Physical Address");
if(pPos2)
{
pPos=strstr(pPos2, ": ");
if(pPos)
{
pPos += 2;
memset(szCmd, 0x00, sizeof(szCmd));
memcpy(szCmd, pPos, 17);
free(pData);
CString strMac = szCmd;
strMac.Replace("-", "");
if(strMac.GetLength()==12) return strMac;
return "";
}
}
}
free(pData);
return "";
}
调用示例:
m_strMAC = GetMacByName("本地连接");
if(m_strMAC.GetLength()==12)
{
m_strLicense = GetLicense(m_strMAC);
}
else
m_strLicense = "";