TheDeveloperBlog.com


C# Dns Class Example

DNS servers resolve host names to IP addresses. With the System.Net namespace in the .NET Framework, we easily perform this task. The Dns.GetHostAddresses method converts a host name to its available IP addresses.


Example. To get started, add the System.Net namespace to the top of your program. Next we use the host name "www.google.com" and pass that string literal to the Dns.GetHostAddresses method. This returns an array of IPAddress classes.

String Literal

Tip: We use the foreach-loop to enumerate the result array. We then call ToString to display our results.

C# program that uses Dns.GetHostAddresses

using System;
using System.Net;

class Program
{
    static void Main()
    {
	IPAddress[] array = Dns.GetHostAddresses("www.google.com");
	foreach (IPAddress ip in array)
	{
	    Console.WriteLine(ip.ToString());
	}
    }
}

Output

74.125.224.82
74.125.224.81
74.125.224.80
74.125.224.84
74.125.224.83

The program prints the IP addresses for the www.google.com host. If you run this program, try pasting an IP address into your web browser. This will resolve to the Google homepage. All of the returned IP addresses resolve to Google.


Summary. We saw the Dns.GetHostAddresses method from the System.Net namespace in the .NET Framework. Sometimes it is useful to have the numeric IP address instead of relying on the host name.

Usually: It is best to use the host name. The host name can be changed to resolve to a different IP address.