I'm looking for a way to change DNS using C++.
The official document I came across is https://learn.microsoft.com/en-us/windows/win32/api/netioapi/nf-netioapi-setinterfacednssettings
But it gives no examples.
The other method I found is
change registry C++ Add DNS entry into network adapter
Not what I need.
C# example How do I change/set DNS with c++?
Funy, there is even a C# example, but no c++.
This method kinda execute some system commands I guess, https://github.com/w123l123h/netConfig
Not what I want neither.
I know I can easily achieve the goal by calling netsh
command.
But, is there some workable examples for SetInterfaceDnsSettings/GetInterfaceDnsSettings
This is my sample code, the returned ret value is always 87, NameServer is NULl.
The interfaceGUID is got from GetAdaptersInfo() api.
void get_dns()
{
GUID interfaceGUID = {0xFD113810, 0x2F5A, 0x4947, {0xA1, 0x19, 0xA5, 0xC9, 0x74, 0x15, 0x88, 0x26}};
DNS_INTERFACE_SETTINGS *settings;
DWORD ret = GetInterfaceDnsSettings(interfaceGUID, settings);
printf("result: %lu\n", ret);
printf("NameServer: %ls\n", settings->NameServer);
}
Follow up question.
SetInterfaceDnsSettings() does not work.
This my code.
GUID interfaceGUID;
LPCOLESTR lpsz = L"{1CA18531-B5FA-4A92-837A-AE12298FFF7F}";
HRESULT hr = CLSIDFromString(lpsz, &interfaceGUID);
if (hr != S_OK)
{
printf("get guid error!!!\n");
exit(1);
}
DNS_INTERFACE_SETTINGS settings = { DNS_INTERFACE_SETTINGS_VERSION1 };
settings.NameServer = L"8.8.8.8";
printf("NameServer: %ls\n", settings.NameServer);
DWORD ret = SetInterfaceDnsSettings(interfaceGUID, &settings);
printf("result: %lu\n", ret);
The ret value returned is 0, I guess it means no error.
But it did not change the DNS of the interface. Whether it's got from GetInterfaceDnsSettings or Control Panel.