如何使用WMI获取PC上所有NIC的MAC地址

时间:2009-09-30 08:48:14

标签: com visual-c++ wmi

全部,

我正在尝试修改MS提供的代码,尝试访问网络适配器配置

当我尝试使用VC ++ 2005访问Mac地址或IPAddress属性时,我得到空指针异常。在这里检查 //异常:vtProp返回为NULL 行在哪里得到例外。

#define _WIN32_DCOM
#include "stdafx.h"

#include <iostream>
using namespace std;
#include <comdef.h>
#include <Wbemidl.h>

# pragma comment(lib, "wbemuuid.lib")
#pragma comment(lib, "comsuppw.lib")

int _tmain(int argc, _TCHAR* argv[])
{
      HRESULT hres;

    // Step 1: --------------------------------------------------
    // Initialize COM. ------------------------------------------

    hres =  CoInitializeEx(0, COINIT_MULTITHREADED); 
    if (FAILED(hres))
    {
        cout << "Failed to initialize COM library. Error code = 0x" 
            << hex << hres << endl;
        return 1;                  // Program has failed.
    }

    // Step 2: --------------------------------------------------
    // Set general COM security levels --------------------------
    // Note: If you are using Windows 2000, you need to specify -
    // the default authentication credentials for a user by using
    // a SOLE_AUTHENTICATION_LIST structure in the pAuthList ----
    // parameter of CoInitializeSecurity ------------------------

    hres =  CoInitializeSecurity(
        NULL, 
        -1,                          // COM authentication
        NULL,                        // Authentication services
        NULL,                        // Reserved
        RPC_C_AUTHN_LEVEL_DEFAULT,   // Default authentication 
        RPC_C_IMP_LEVEL_IMPERSONATE, // Default Impersonation  
        NULL,                        // Authentication info
        EOAC_NONE,                   // Additional capabilities 
        NULL                         // Reserved
        );


    if (FAILED(hres))
    {
        cout << "Failed to initialize security. Error code = 0x" 
            << hex << hres << endl;
        CoUninitialize();
        return 1;                    // Program has failed.
    }

    // Step 3: ---------------------------------------------------
    // Obtain the initial locator to WMI -------------------------

    IWbemLocator *pLoc = NULL;

    hres = CoCreateInstance(
        CLSID_WbemLocator,             
        0, 
        CLSCTX_INPROC_SERVER, 
        IID_IWbemLocator, (LPVOID *) &pLoc);

    if (FAILED(hres))
    {
        cout << "Failed to create IWbemLocator object."
            << " Err code = 0x"
            << hex << hres << endl;
        CoUninitialize();
        return 1;                 // Program has failed.
    }

    // Step 4: -----------------------------------------------------
    // Connect to WMI through the IWbemLocator::ConnectServer method

    IWbemServices *pSvc = NULL;

    // Connect to the root\cimv2 namespace with
    // the current user and obtain pointer pSvc
    // to make IWbemServices calls.
    hres = pLoc->ConnectServer(
         _bstr_t(L"ROOT\\CIMV2"), // Object path of WMI namespace
         NULL,                    // User name. NULL = current user
         NULL,                    // User password. NULL = current
         0,                       // Locale. NULL indicates current
         NULL,                    // Security flags.
         0,                       // Authority (e.g. Kerberos)
         0,                       // Context object 
         &pSvc                    // pointer to IWbemServices proxy
         );

    if (FAILED(hres))
    {
        cout << "Could not connect. Error code = 0x" 
             << hex << hres << endl;
        pLoc->Release();     
        CoUninitialize();
        return 1;                // Program has failed.
    }

    cout << "Connected to ROOT\\CIMV2 WMI namespace" << endl;


    // Step 5: --------------------------------------------------
    // Set security levels on the proxy -------------------------

    hres = CoSetProxyBlanket(
       pSvc,                        // Indicates the proxy to set
       RPC_C_AUTHN_WINNT,           // RPC_C_AUTHN_xxx
       RPC_C_AUTHZ_NONE,            // RPC_C_AUTHZ_xxx
       NULL,                        // Server principal name 
       RPC_C_AUTHN_LEVEL_CALL,      // RPC_C_AUTHN_LEVEL_xxx 
       RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx
       NULL,                        // client identity
       EOAC_NONE                    // proxy capabilities 
    );

    if (FAILED(hres))
    {
        cout << "Could not set proxy blanket. Error code = 0x" 
            << hex << hres << endl;
        pSvc->Release();
        pLoc->Release();     
        CoUninitialize();
        return 1;               // Program has failed.
    }

    // Step 6: --------------------------------------------------
    // Use the IWbemServices pointer to make requests of WMI ----

    // For example, get the name of the operating system
    IEnumWbemClassObject* pEnumerator = NULL;
    hres = pSvc->ExecQuery(
        bstr_t("WQL"), 
        bstr_t("SELECT * FROM Win32_NetworkAdapterConfiguration"),
        WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, 
        NULL,
        &pEnumerator);

    if (FAILED(hres))
    {
        cout << "Query for NIC(s) name failed."
            << " Error code = 0x" 
            << hex << hres << endl;
        pSvc->Release();
        pLoc->Release();
        CoUninitialize();
        return 1;               // Program has failed.
    }

    // Step 7: -------------------------------------------------
    // Get the data from the query in step 6 -------------------

    IWbemClassObject *pclsObj;
    ULONG uReturn = 0;

    while (pEnumerator)
    {
        HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1, 
            &pclsObj, &uReturn);

        if(0 == uReturn)
        {
            break;
        }

        VARIANT vtProp;

        // Get the value of the Name property

        //hr = pclsObj->Get(L"Caption", 0, &vtProp, 0, 0);
  //      wcout << " Caption : " << vtProp.bstrVal << endl;
  //      VariantClear(&vtProp);
     //   pclsObj->Release();

        hr = pclsObj->Get(L"MACAddress", 0, &vtProp, 0, 0);
        // exception here:  vtProp is returned as NULL
        wcout << " MACAddress : " << vtProp.bstrVal << endl;
        VariantClear(&vtProp);
        pclsObj->Release();


    }

    // Cleanup
    // ========

    pSvc->Release();
    pLoc->Release();
    pEnumerator->Release();
   // pclsObj->Release();
    CoUninitialize();

    return 0;   // Program successfully completed.
}

代码中出了什么问题?

Abdul khaliq

3 个答案:

答案 0 :(得分:2)

这是旧的,但我有同样的问题,我没有看到任何解决方案。我通过检查VT_NULL来解决它。

if( vtProp.vt != VT_NULL )
    wcout << " MACAddress : " << vtProp.bstrVal << endl;

我不明白为什么有些结果是VT_NULL但我怀疑可以通过在“select”语句中添加“where”子句来避免这种情况。

感谢finnw提示!

答案 1 :(得分:0)

我首先要初始化vtProp变量 - 它应该没关系,但有时候COM服务器会假设有关params;

  VariantInit(&vtProp);

然后你可以在它被返回后检查vtProp并查看实际类型是什么(.vt成员) - 也许它不是字符串,出于某种原因?

您可以使用该类型回发(您可以使用oaidl.h中的VARTYPE定义进行交叉引用,以查看友好名称是什么)?

答案 2 :(得分:0)

网络适配器列表通常包含一些“虚拟”适配器,并且它们并非都具有MAC地址。一些(例如“数据包调度程序微型端口”)复制物理适配器的MAC地址。您只需要检查vt字段(可能是VT_EMPTY)并从结果列表中删除重复项。