2016年6月15日 星期三

Windows:識別唯一電腦的方式(The Best Way To Uniquely Identify A Windows Machine)

假設今天做一個產品,要綁定一台電腦當作唯一的識別,通常想到的就是找出該電腦網路介面卡的MAC Address,但是有可能網路卡會換,或者是擴充很多張網卡,那該怎麼辦?


後來windows 就提供了一個Machine GUID(Globally Unique Identifier),來作唯一的識別

從登錄檔裡HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography路徑下可以觀察到,如圖

取得machine GUID的VC++程式碼如下:

#include <windows.h>
#include <stdio.h>
int main()
{
 HKEY hky;
 LONG ern;
 DWORD typ = REG_SZ;
 DWORD siz;
 CHAR dat[37];
 siz = sizeof dat;
 ern = RegOpenKeyExA(HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Cryptography", 0, KEY_WRITE | KEY_READ | KEY_WOW64_64KEY, &hky);
 if (ERROR_SUCCESS == ern) {
  ern = RegQueryValueExA(hky, "MachineGuid", NULL, &typ, (LPBYTE)dat, &siz);
  RegCloseKey(hky);
  if (ERROR_SUCCESS == ern) {
   if (typ != REG_SZ) { printf("Error: The MachineGuid value is not of the expected type.\n"); return 1; }
   if (sizeof dat != siz || dat[sizeof dat - 1] || sizeof dat - 1 != strlen(dat)) { printf("Error: The MachineGuid value is shorter than expected, is missing the terminating null, or contains embedded nulls.\n"); return 1; }
   printf("%s\n", dat);
   system("pause");
   return 0;
  }
  else {
   if (ERROR_MORE_DATA == ern) { printf("Error: The MachineGuid value is longer than expected.\n"); return 1; }
   printf("RegQueryValueExA: ");
  }
 }
 else { printf("RegOpenKeyExA: "); }
 LPVOID lpMsgBuf;
 FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, ern, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&lpMsgBuf, 0, NULL);
 printf("Error 0x%u: %s\n", (UINT)ern, (LPSTR)lpMsgBuf);
 LocalFree(lpMsgBuf);
 system("pause");
 return 1;
}
參考資料 : The Best Way To Uniquely Identify A Windows Machine
             Print MachineGuid

沒有留言:

張貼留言