On enabling Network adpater, Autoconfiguration IP

2019-09-04 07:38发布

问题:

I am developing an application for Windows Vista and 7 in Visual Studio C++, in which i have to assign static IP address to a network card and establish a connection. For this, I am entering the Ip values in registry along with setting the Enable DHCP value to 0. Then i need to disable and then enable the network card for these values to take effect. For this, I am using "INetConnectionManager" in the following code:

  CoInitialize(0);
  typedef void (__stdcall * PNcFreeNetconProperties)(NETCON_PROPERTIES* pProps);
  HMODULE hmod = LoadLibrary(L"netshell.dll");
  if (!hmod) 
    return false;

  LPNcFreeNetconProperties NcFreeNetconProperties =
    (LPNcFreeNetconProperties)GetProcAddress(hmod, "NcFreeNetconProperties");

  if (!NcFreeNetconProperties )
    return false;

  INetConnectionManager * pMan = 0;

  HRESULT hres = CoCreateInstance(CLSID_ConnectionManager,
                  0,
                  CLSCTX_ALL,
                  __uuidof(INetConnectionManager),
                  (void**)&pMan);

  if (SUCCEEDED(hres))  
  {    
      IEnumNetConnection * pEnum = 0;
      hres = pMan->EnumConnections(NCME_DEFAULT, &pEnum);
     if (SUCCEEDED(hres)) 
     {
         INetConnection * pCon = 0;
         ULONG count;
         bool done = false;
         while (pEnum->Next(1, &pCon, &count) == S_OK && !done)
         {
             NETCON_PROPERTIES * pProps = 0;
             hres = pCon->GetProperties(&pProps);
             if (SUCCEEDED(hres)) 
             {
                 if (wcscmp(pProps-pszwDeviceName, AdapterName) == 0)
                 {
                     if (bEnable)
                         result = (pCon->Connect() == S_OK);
                     else
                         result = (pCon->Disconnect() == S_OK);
                     done = true;
                 }

                 NcFreeNetconProperties(pProps);
              }
              pCon->Release();
         }
         pEnum->Release();
     }
    pMan->Release();
  }
  FreeLibrary(hmod);
  CoUninitialize();

Its disabling and enabling the network card very well, BUT the autoconfiguration IPv4 values are getting set instead of the static values in the registry. This strangely works properly for DHCP connection but not for static connection.

NOTE : I even tried SetIfEntry for it, but it fails to disable or enable Network Card.

Please suggest where I am doing wrong or anything I am missing.

Thanks and Regards,

Vinayak

回答1:

You can use AddIPAddress:

http://msdn.microsoft.com/en-us/library/aa365801%28v=vs.85%29.aspx



回答2:

Does INetConnectionManager supported on Windows VISTA and Win7? I have implemented the same code what you have written here but I get access denied for pCon->Connect when application runs on non admin login. Therefore, it looks like that we need to elevate the com object using COM Moniker.

Regards IP_Telephony