Recipe14.1.Converting an IP Address to a Hostname


Recipe 14.1. Converting an IP Address to a Hostname

Problem

You have an IP address that you need to resolve into a hostname.

Solution

Use the Dns.GetHostEntry method to get the hostname for an IP address. In the following code, an IP address is resolved, and the hostname is accessible from the HostName property of the IPHostEntry:

 using System; using System.Net; //… // Use the Dns class to resolve the address. IPHostEntry iphost = Dns.GetHostEntry("127.0.0.1"); // HostName property holds the hostname. string hostName = iphost.HostName; // Print out name. Console.WriteLine(hostName); 

Discussion

The System.Net.Dns class is provided for simple DNS resolution functionality. The GetHostEntry method returns an IPHostEntry that can be used to access the hostname via the HostName property. If the entry cannot be resolved, the IPHostEntry will have a HostName that has a string representation of the IP address that was passed in (assuming it is a valid IP address). If the first member of the AddressList ([0]) is accessed and the IPAddress.ScopeId property is checked for these entries, it will throw a SocketException.

See Also

See the "DNS Class" and "IPHostEntry Class" topics in the MSDN documentation.



C# Cookbook
Secure Programming Cookbook for C and C++: Recipes for Cryptography, Authentication, Input Validation & More
ISBN: 0596003943
EAN: 2147483647
Year: 2004
Pages: 424

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