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

前端 未结 2 1940
难免孤独
难免孤独 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");
            }
        }
    }
    
    0 讨论(0)
  • 2021-01-04 07:14

    See the MSDN on IPInterfaceProperties.DnsAddresses for sample code.

    0 讨论(0)
提交回复
热议问题