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



Add Yours
YOU