要做这件事情需要两个步骤, 第一步获取活动的连接, 第二部修改DNS:
int SetLocalDNS(CString csPrimaryDns, CString csBackupDns)
{
INetConnectionManager *pManager=NULL;
IEnumNetConnection *pEnum=NULL;
INetConnection *pConnection=NULL;
ULONG celtFetched;
NETCON_PROPERTIES* properties=NULL;
CoInitialize(NULL);
CoCreateInstance(CLSID_ConnectionManager, NULL, CLSCTX_SERVER, IID_INetConnectionManager, (void**)&pManager);
if(pManager == NULL)
{
return 0;
}
pManager->EnumConnections(NCME_DEFAULT, &pEnum);
while( pEnum->Next(1, &pConnection, &celtFetched) == S_OK )
{
pConnection->GetProperties(&properties);
if(properties->Status == NCS_CONNECTED)
{
CString csPrimaryDnsCmd,csBackupDnsCmd;
csPrimaryDnsCmd.Format(L"cmd /c netsh interface ip set dns \"%s\" static \"%s\"",properties->pszwName,csPrimaryDns);
csBackupDnsCmd.Format(L"netsh interface ip add dns \"%s\" \"%s\"",properties->pszwName,csBackupDns);
CString DNSCmd = csPrimaryDnsCmd + L"&"+csBackupDnsCmd;
if ( 33>(int)ShellExecute(NULL,L"open",L"cmd.exe",DNSCmd,NULL,SW_HIDE))
{
OutputDebugString(L"Set Local Dns Error.\r\n");
}
}
}
if(pManager) pManager->Release();
if(pConnection) pConnection->Release();
if(pEnum) pEnum->Release();
CoUninitialize();
}
循环获取本地的网络连接并且判断连接状态, 然后根据连接名称调用cmd修改链接的DNS, 当然其他属性比如IP和网关也是可以修改的。