Get Local DNS Server Address using C#

In this example we will get the DNS server address that is configured on your local network adapter. Start by getting all the Network Interfaces, loop over them to find one which has an OperationalStatus of Up, then get the IPInterfaceProperties of the active NetworkInterface, then get the DNS Addresses from the IPInterfaceProperties and then return the first value.


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



Comments

No comments yet.

Add Yours

  • Author Avatar

    YOU


Comment Arrow




About Author

Robert

Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning hands down.