Finding DNS servers using c#
Filed Under (c#, net) by The Chef on 06-06-2009
Tagged Under : .net framework, c#, dns
Every computer connected to the internet must interrogate a DNS server in order to resolve domain names to ip addresses. To find the DNS server addresses your computer uses to resolve names, either it has a dhcp or static ip address, you can use the following piece of code. I wrapped all around a nice static class for ease of use.
public static class DNSFinder
{
private static List<String> mServers = new List<string>();
public static List<String> Servers
{
get
{
RegistryKey start = Registry.LocalMachine;
string DNSservers = @"SYSTEM\CurrentControlSet\Services\Tcpip\Parameters";
RegistryKey DNSserverKey = start.OpenSubKey(DNSservers);
if (DNSserverKey != null)
{
// Static ip address
string serverlist = (string)DNSserverKey.GetValue("NameServer");
string[] servers = serverlist.Split(' ');
foreach (string server in servers)
{
mServers.Add(server);
}
//dhcp assigned address
serverlist = (string)DNSserverKey.GetValue("DhcpNameServer");
servers = serverlist.Split(' ');
foreach (string server in servers)
{
mServers.Add(server);
}
start.Close();
}
DNSserverKey.Close();
return mServers;
}
}