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

Com 如何使用WMI获取PC上所有NIC的MAC地址,com,visual-c++,wmi,Com,Visual C++,Wmi,大家好 我正在尝试修改MS提供的代码,尝试访问网络适配器配置 当我尝试使用VC++2005访问Mac地址或IPAddress属性im时,它中出现空指针异常。在此处检查//异常:vtProp作为NULL行返回,我在其中获取异常 #define _WIN32_DCOM #include "stdafx.h" #include <iostream> using namespace std; #include <comdef.h> #include <Wbemidl.h&

大家好

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

当我尝试使用VC++2005访问Mac地址或IPAddress属性im时,它中出现空指针异常。在此处检查//异常: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.
}
\define\u WIN32\u DCOM
#包括“stdafx.h”
#包括
使用名称空间std;
#包括
#包括
#pragma注释(lib,“wbemuid.lib”)
#pragma注释(lib,“comsuppw.lib”)
int _tmain(int argc,_TCHAR*argv[]
{
HRESULT hres;
//步骤1:--------------------------------------------------
//初始化COM------------------------------------------
hres=CoInitializeX(0,Conit_多线程);
如果(失败(hres))
{

cout我首先初始化
vtProp
变量——这不重要,但有时COM服务器会对out参数进行假设

  VariantInit(&vtProp);
然后,您可以在返回后检查
vtProp
,看看实际的类型是什么(
.vt
成员)——出于某种原因,它可能不是字符串


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

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

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

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

wcout在执行该行后,
hr=pclsObj->Get(L“MACAddress”,0,&vtProp,0,0)之后,
hr的值是多少;
?hr的值S_OK