Home > Software engineering >  How do I change/set DNS with c ?
How do I change/set DNS with c ?

Time:09-18

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.

CodePudding user response:

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();
  • Related