std::string GetHardwareSerialNumber()
{
std::string sResult;
const long COMMAND_SIZE = 1020;
const DWORD WAIT_TIME = 1000; // INFINITE
// 获取主板序列号
TCHAR szFetCmd[] = _T("wmic BaseBoard get SerialNumber");// 命令行
const std::string strEnSearch = "SerialNumber"; // 前导信息
// 获取BIOS序列号
//TCHAR szFetCmd[] = _T("wmic bios get serialnumber");// 命令行
//const std::string strEnSearch = "SerialNumber"; // 前导信息
// 获取CPU序号名
//TCHAR szFetCmd[] = "wmic cpu get processorid"; // 命令行
//const string strEnSearch = "ProcessorId"; // 前导信息
BOOL bReturnCode = FALSE;
HANDLE hReadPipe = NULL; // Pipeline for READ
HANDLE hWritePipe = NULL; // Pipeline for WRITE
PROCESS_INFORMATION pi; // Process information
STARTUPINFO si; // Control-command window info
SECURITY_ATTRIBUTES sa; // Security attributes
char szBuffer[COMMAND_SIZE + 1] = { 0 }; // Command line output buffer
std::string strBuffer;
DWORD count = 0;
size_t pos = 0;
size_t i = 0;
size_t j = 0;
char* lpszBaseBoard = (char*)malloc((COMMAND_SIZE + 1)*sizeof(char));
memset(lpszBaseBoard, 0x00, (COMMAND_SIZE + 1)*sizeof(char));
memset(&pi, 0, sizeof(pi));
memset(&si, 0, sizeof(si));
memset(&sa, 0, sizeof(sa));
pi.hProcess = NULL;
pi.hThread = NULL;
si.cb = sizeof(STARTUPINFO);
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.lpSecurityDescriptor = NULL;
sa.bInheritHandle = TRUE;
bReturnCode = CreatePipe(&hReadPipe, &hWritePipe, &sa, 0);
if (!bReturnCode)
goto EXIT;
GetStartupInfo(&si);
si.hStdError = hWritePipe;
si.hStdOutput = hWritePipe;
si.wShowWindow = SW_HIDE; // hide command line window
si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
bReturnCode = CreateProcess(NULL, szFetCmd, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi);
if (!bReturnCode)
goto EXIT;
WaitForSingleObject(pi.hProcess, WAIT_TIME);
bReturnCode = ReadFile(hReadPipe, szBuffer, COMMAND_SIZE, &count, 0);
if (!bReturnCode)
goto EXIT;
bReturnCode = FALSE;
strBuffer = szBuffer;
pos = strBuffer.find(strEnSearch);
if (pos < 0) // NOT FOUND
goto EXIT;
else
strBuffer = strBuffer.substr(pos + strEnSearch.length());
memset(szBuffer, 0x00, sizeof(szBuffer));
strcpy_s(szBuffer, strBuffer.c_str());
j = 0;
for (i = 0; i < strlen(szBuffer); i++)
{
if (szBuffer[i] != ' ' && szBuffer[i] != '\n' && szBuffer[i] != '\r')
{
lpszBaseBoard[j] = szBuffer[i];
j++;
}
}
sResult = lpszBaseBoard;
bReturnCode = TRUE;
EXIT:
free(lpszBaseBoard);
CloseHandle(hWritePipe);
CloseHandle(hReadPipe);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
return sResult;
}