How do I get my current DNS Server in C#?

前端 未结 2 1952
难免孤独
难免孤独 2021-01-04 06:40

How do I get my current DNS Server in C#?

2条回答
  •  春和景丽
    2021-01-04 07:07

    I was recently trying to do the same thing and found this excellent example by Robert Sindal.

    using System;
    using System.Net;
    using System.Net.NetworkInformation;
    
    namespace HowToGetLocalDnsServerAddressConsoleApp
    {
        class Program
        {
            static void Main(string[] args)
            {
                Console.WriteLine(GetDnsAdress());
                Console.ReadKey();
            }
    
            private static IPAddress GetDnsAdress()
            {
                NetworkInterface[] networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
    
                foreach (NetworkInterface networkInterface in networkInterfaces)
                {
                    if (networkInterface.OperationalStatus == OperationalStatus.Up)
                    {
                        IPInterfaceProperties ipProperties = networkInterface.GetIPProperties();
                        IPAddressCollection dnsAddresses = ipProperties.DnsAddresses;
    
                        foreach (IPAddress dnsAdress in dnsAddresses)
                        {
                            return dnsAdress;
                        }
                    }
                }
    
                throw new InvalidOperationException("Unable to find DNS Address");
            }
        }
    }
    

提交回复
热议问题