This sample piece of code has two purposes:
- It will give you a general background on why to use all this rich set of WMI classes in C++.
- It will demonstrate an alternative method for obtaining a MAC address of the network card of the computer.
I stumbled upon this problem while I was using the RPC function
UuidCreateSequential from Platform SDK when suddenly on several computers it began to give different MACs every time. Then I found this statement on MSDN:
"For security reasons,
UuidCreate was modified so that it no longer uses a machine's MAC address to generate UUIDs."
So I had to find an alternative method. One was to use the
NetBIOS function, but firstly, it's quite complicated and secondly, not every machine has
NetBIOS installed. So I turned to the WMI alternative which turned to be quite simple.
Using the Code
In the attached ZIP file, you will find a console application that just prints out all the network cards MACs. All the code is in the main function, so here it is with some explanations:
int _tmain(int argc, _TCHAR* argv)
if (locator != NULL)
WbemScripting::ISWbemServicesPtr services =
WbemScripting::ISWbemObjectSetPtr objects =
services->ExecQuery("Select * from Win32_NetworkAdapter",
IEnumVARIANTPtr obj_enum = objects->Get_NewEnum();
while (obj_enum->Next(1,&var,&fetched) == S_OK)
WbemScripting::ISWbemObjectPtr object = var;
WbemScripting::ISWbemPropertySetPtr properties = object->Properties_;
WbemScripting::ISWbemPropertyPtr prop =
_variant_t value = prop->GetValue();
if (value.vt == VT_I4 && (int)value == 0)
prop = properties->Item("MACAddress",0);
printf("MAC address found: %s\n",
catch (_com_error err)
printf("Error occurred: %S",err.ErrorMessage());
- 25th March, 2007: Initial post