开发者

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

开发者 https://www.devze.com 2022-12-31 08:31 出处:网络
How 开发者_运维知识库do I get my current DNS Server in C#?See the MSDN on IPInterfaceProperties.DnsAddresses for sample code.I was recently trying to do the same thing and found this excellent example

How 开发者_运维知识库do I get my current DNS Server in C#?


See the MSDN on IPInterfaceProperties.DnsAddresses for sample code.


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");
        }
    }
}


This method determines the configured dns server addresses on all interfaces which are "up". It allows the choice if IPv4 and / or IPv6 addresses are wanted.

using System.Net.NetworkInformation;
using System.Net.Sockets;

public static IPAddress[] GetDnsAdresses(bool ip4Wanted, bool ip6Wanted)
{
    NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
    HashSet<IPAddress> dnsAddresses = new HashSet<IPAddress>();

    foreach (NetworkInterface networkInterface in interfaces)
    {
        if (networkInterface.OperationalStatus == OperationalStatus.Up)
        {
            IPInterfaceProperties ipProperties = networkInterface.GetIPProperties();

            foreach (IPAddress forAddress in ipProperties.DnsAddresses)
            {
                if ((ip4Wanted && forAddress.AddressFamily == AddressFamily.InterNetwork) || (ip6Wanted && forAddress.AddressFamily == AddressFamily.InterNetworkV6))
                {
                    dnsAddresses.Add(forAddress);
                }
            }
        }
    }

    return dnsAddresses.ToArray();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消