Few days ago I was writting an application querying DNS for MX record. Trying to optimize it, I realize I could use the DNS specified for the local computer instead of using a hard-coded one. Then I wonder how to get this DNS server list and, most important, how to keep it up-to-date. Because changing of wi-fi hotspot makes my IP settings (IP Address, Subnet Mask, and… DNS servers) change.
This snippet first queries for all available network interface.
Then, for each interface whom status is up and whom type is not tunnel neither loopback, queries for its DNS server list.
public static ArrayList GetLocalDnsServerList() { ArrayList DNSServers = new ArrayList(); // Get the List of DNS used by all available network interface NetworkInterface[] arrNetInterfaces = NetworkInterface.GetAllNetworkInterfaces(); Trace.WriteLine("Trying to retreive local dns servers list...", false); foreach (NetworkInterface item in arrNetInterfaces) { if ((item.OperationalStatus == OperationalStatus.Up) (item.Speed > 0) (item.NetworkInterfaceType != NetworkInterfaceType.Loopback) (item.NetworkInterfaceType != NetworkInterfaceType.Tunnel)) { foreach (IPAddress objDNSAddress in item.GetIPProperties().DnsAddresses) { if (objDNSAddress.AddressFamily == AddressFamily.InterNetwork) try { IPHostEntry IpEntry = Dns.GetHostEntry(objDNSAddress.ToString()); Trace.WriteLine("\t" + IpEntry.HostName.ToString() + " (" + objDNSAddress.ToString() + ")", false); DNSServers.Add(objDNSAddress.ToString()); } catch (SocketException e) { Trace.WriteLine("Exception when trying to retreive local dns servers list. " + "Network might not be available.\r\n" + "System returns: " + e.Message + (e.InnerException != null?" " + e.InnerException.Message : ""), false); } } } } if (DNSServers.Count == 0) Trace.WriteLine("Warning: DNS servers list is empty. Network might not be available."); return DNSServers; }
Now we have to be aware about network availability change by adding a new event handler:
public static ArrayList arDNSList = new ArrayList();</code> NetworkChange.NetworkAddressChanged += new NetworkAddressChangedEventHandler(NetworkChangedCallback); ... private static void NetworkChangedCallback(object sender, EventArgs e) { arDNSList = GetLocalDnsServerList(); }
In a futur post, I’ll explain how to use this list to query for MX record. Stay tuned!