.NET DNS Class

Continuing with the theme of the last post, which covered the IPAddress class, this week we will take a look at the DNS class. The DNS class also lives in the System.Net namespace and helps simplify working with DNS servers to resolve IP addresses and hostnames. Whether you need to know the IP Address from the hostname, or you have a hostname and you need to know the IP Address, the DNS class will help make DNS resolution simple.

To retrieve IP addresses via the hostname:

IPAddress[] ipAddresses = Dns.GetHostAddresses("jamessturtevant.com");

Assert.AreEqual("", ipAddresses.First().ToString());

To get the host namevia the IP address:

// May fail if IP changes
IPHostEntry hostEntry = Dns.GetHostEntry("");

Assert.AreEqual("github.com", hostEntry.HostName);

More Information

The above functions show how to make synchronous calls but the DNS class has recently been given asynchronous support. You can find the asynchronous version and more information about the DNS class on the MSDN page. You can also find runnable examples on my .NET Framework Tour GitHub repository.


comments powered by Disqus