11.6 Resolve a Host Name to an IP Address


11.6 Resolve a Host Name to an IP Address

Problem

You want to determine the IP address for a computer based on its domain name by performing a Domain Name System (DNS) query.

Solution

Use GetHostByName method of the System.Net.Dns class, and pass the domain name as a string parameter.

Discussion

On the Web, publicly accessible IP addresses are often mapped to host names that are easier to remember. For example, the IP address 207.171.185.16 might be mapped to the domain name www.amazon.com. To determine the IP address for a given name, the computer contacts a DNS server.

The entire process of name resolution is transparent if you use the System.Net.Dns class, which allows you to retrieve the IP address for a host name by calling GetHostByName . Here's how you might retrieve the list of IP addresses mapped to www.microsoft.com:

 using System; using System.Net; public class ResolveIP {     private static void Main() {         foreach (IPAddress ip in            Dns.GetHostByName("www.microsoft.com").AddressList) {             Console.Write(ip.AddressFamily.ToString() + ": ");             Console.WriteLine(ip.ToString());         }         Console.ReadLine();     } } 

This test produces output similar to the following:

 InterNetwork: 207.46.249.222 InterNetwork: 207.46.134.222 InterNetwork: 207.46.249.27 InterNetwork: 207.46.134.155 InterNetwork: 207.46.249.190 



C# Programmer[ap]s Cookbook
C# Programmer[ap]s Cookbook
ISBN: 735619301
EAN: N/A
Year: 2006
Pages: 266

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net