2021年7月5日月曜日

win32 C++ でWMI(Windows Management Instrumentation)を使用する

以下は指定IP(szIPaddr)に ping を打った時の status を取得する

// 主スレッドで呼出し
CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_DEFAULT, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE, 0);

// Ping status
HRESULT hr;
CComPtr< IWbemLocator > pLocator;
hr = CoCreateInstance(CLSID_WbemAdministrativeLocator, NULL, CLSCTX_INPROC_SERVER, IID_IWbemLocator, (void**)(&pLocator));
if (SUCCEEDED(hr))
{
  CComPtr< IWbemServices > pService;
  //hr = pLocator->ConnectServer(L"root\\cimv2", NULL, NULL, NULL, WBEM_FLAG_CONNECT_USE_MAX_WAIT, NULL, NULL, &pService);
  hr = pLocator->ConnectServer(L"root\\cimv2", NULL, NULL, NULL, 0, NULL, NULL, &pService);
  if (SUCCEEDED(hr))
  {
    CString szSQL;
    szSQL.Format(_T("SELECT * FROM Win32_PingStatus WHERE Address='%s'"), szIPaddr);
    _bstr_t bzSQL(_bstr_t(CT2W((LPCTSTR)szSQL)));
    CComPtr< IEnumWbemClassObject > pEnumObj;
    hr = pService->ExecQuery(L"WQL", bzSQL, (WBEM_FLAG_RETURN_IMMEDIATELY|WBEM_FLAG_FORWARD_ONLY), NULL, &pEnumObj);
    if (SUCCEEDED(hr))
    {
      CComPtr< IWbemClassObject > pObj;
      ULONG uReturned;
      //hr = pEnumObj->Reset();
      hr = pEnumObj->Next(WBEM_INFINITE, 1, &pObj, &uReturned);
      if (!FAILED(hr))
      {
        _variant_t vtBuf;
        hr = pObj->Get(L"StatusCode", 0, &vtBuf, 0, 0);
        pObj.Release();
      }
      pEnumObj.Release();
    }
    pService.Release();
  }
  pLocator.Release();
}

0 件のコメント: