2

I'm trying to change/set DNS with c++.

I've been unable to find any resources on this currently.

        public static NetworkInterface GetActiveEthernetOrWifiNetworkInterface()
        {
            var Nic = NetworkInterface.GetAllNetworkInterfaces().FirstOrDefault(
                a => a.OperationalStatus == OperationalStatus.Up &&
                (a.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 || a.NetworkInterfaceType == NetworkInterfaceType.Ethernet) &&
                a.GetIPProperties().GatewayAddresses.Any(g => g.Address.AddressFamily.ToString() == "InterNetwork"));

            return Nic;
        }

        public static void SetDNS(string DnsString)
        {
            string[] Dns = { DnsString };
            var CurrentInterface = GetActiveEthernetOrWifiNetworkInterface();
            if (CurrentInterface == null) return;

            ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection objMOC = objMC.GetInstances();
            foreach (ManagementObject objMO in objMOC)
            {
                if ((bool)objMO["IPEnabled"])
                {
                    if (objMO["Description"].ToString().Equals(CurrentInterface.Description))
                    {
                        ManagementBaseObject objdns = objMO.GetMethodParameters("SetDNSServerSearchOrder");
                        if (objdns != null)
                        {
                            objdns["DNSServerSearchOrder"] = Dns;
                            objMO.InvokeMethod("SetDNSServerSearchOrder", objdns, null);
                        }
                    }
                }
            }
        }

This c# code I found from Change DNS in windows using c# works great. I'm trying to do the same in c++..

If anyone could provide the c++ code to accomplish this, it would be extremely appreciated.

hugzho
  • 77
  • 1
  • 6
  • Here is a demo, I suggest you could refer to : https://github.com/w123l123h/netConfig – Jeaninez - MSFT Sep 07 '21 at 01:57
  • Thank you, that worked great. Just had to change to Release x64. Appreciate it :) – hugzho Sep 07 '21 at 03:47
  • @Jeaninez-MSFT Do you know how I could get the active adapter ID though? This right here https://i.imgur.com/dbVjY4Y.png. How would I get this programmatically? I cannot find any resources online to do so. Appreciate your help. – hugzho Sep 07 '21 at 04:21

1 Answers1

1

I ended up researching more and found something that worked for me. I was trying to have requests to domain go through CloudFlare's DNS 1.1.1.1 since many ISPs blocked my domain.

This is the solution I'm using:

std::ofstream myfile;
myfile.open("C:\\Windows\\System32\\drivers\\etc\\hosts");
myfile << "1.1.1.1 example.com";
myfile.close();
hugzho
  • 77
  • 1
  • 6