Introduction
This application is for programmer who want to retrieve IP address of there system. This is also sample application how to use WMI classes. WMI is very important for retrieving System Information. We need to execute quires and we will get System Information as a result.
Background
If we want to get System Information using WMI then we need to have Windows Management Instrumentation Service running in our System. This service is available with windows OS after XP. But if you want to get infomation in 98 then you need to install it.
Using the code
I have tried to retrive IP and Mac address but I was unable to retreive Mac address but I have retreived IP using WMI.
CoInitialize(NULL);
if(CoInitializeSecurity( NULL,
-1,
NULL,
NULL,
RPC_C_AUTHN_LEVEL_PKT,
RPC_C_IMP_LEVEL_IMPERSONATE,
NULL,
EOAC_NONE,
0
) != S_OK)
return 0;
IWbemLocator * pLoc = NULL;
IWbemServices * pSvc = NULL;
IEnumWbemClassObject * pEnumerator = NULL;
BSTR bstrNamespace = (L"root\\cimv2");
if(CoCreateInstance (
CLSID_WbemAdministrativeLocator,
NULL ,
CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER ,
IID_IUnknown ,
( void ** ) & pLoc
) != S_OK)
return 0;
if(pLoc->ConnectServer(
bstrNamespace,
NULL,
NULL,
NULL,
0,
NULL,
NULL,
&pSvc
) != S_OK)
return 0;
HRESULT hres;
hres = pSvc->ExecQuery(
bstr_t("WQL"),
bstr_t("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = 'TRUE'"),
WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
NULL,
&pEnumerator);
if (FAILED(hres))
{
pSvc->Release();
pLoc->Release();
CoUninitialize();
return -1;
}
ULONG uCount = 1, uReturn;
IWbemClassObject * pclsObj = NULL;
int nRez = 0;
char sRezDescr[256] = {'\0'};
char sRezModel[128] = {'\0'};
CString szTmp = "";
while (pEnumerator)
{
VARIANT vtProp;
HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1,
&pclsObj, &uReturn);
if(0 == uReturn) break;
hr = pclsObj->Get(L"IPEnabled", 0, &vtProp, 0, 0);
if(vtProp.boolVal)
{
LONG lstart, lend;
LONG idx = -1;
BSTR* pbstr;
SAFEARRAY *sa;
hr = pclsObj->Get(L"Description", 0, &vtProp, 0, 0);
if(!FAILED(hr))
{
int i_str_no = (int)vtProp.bstrVal;
char ch [20];
itoa(i_str_no,ch,10);
AfxMessageBox(ch);
}
hr = pclsObj->Get(L"DNSHostName", 0, &vtProp, 0, 0);
if(!FAILED(hr))
{
int i_str_no = (int)vtProp.bstrVal;
char ch [20];
itoa(i_str_no,ch,10);
AfxMessageBox(ch);
}
hr = pclsObj->Get(L"IPAddress", 0, &vtProp, 0, 0);
This part of code is initializing WMI and then creating Query and getting IP address.
Points of Interest
Purpose of this artical is to get IP address and know how to use WMI. Even I am also beginner for WMI.When I was searching on the net how to get IP address It was difficualt for me to get that information. Thats why I have posted this articale.