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. An array of IPAddress
instances is returned.
Please add the System.Net
namespace to the top of your program. We use a host name and pass it to the Dns.GetHostAddresses
method. This returns an array of IPAddress
classes.
foreach
-loop to enumerate the result array. We then call ToString
to display our results.using System; using System.Net; class Program { static void Main() { IPAddress[] array = Dns.GetHostAddresses("en.wikipedia.org"); foreach (IPAddress ip in array) { Console.WriteLine(ip.ToString()); } } }2620:0:863:ed1a::1 198.35.26.96
The program prints the IP addresses for the English Wikipedia host. Try pasting the IP address into your web browser. It will be associated with Wikipedia.
We saw the Dns.GetHostAddresses
method from the System.Net
namespace. Sometimes it is useful to have the numeric IP address instead of relying on the host name.
For most programs, it is best to use the host name. The host name can be changed to resolve to a different IP address. This is more reliable.