
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Converting a Hostname to an IP Address
|
791
// 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 host-
name 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.
14.2 Converting a Hostname to an IP Address
Problem
You have a string representation of a host (such as www.oreilly.com), and you need
to obtain the IP address from this hostname.
Solution
Use the Dns.GetHostEntry method to get the IP addresses. In the following code, a
hostname is provided to the
GetHostEntry method, which returns an IPHostEntry
from which a string of addresses can be constructed. If the hostname does not
resolve, ...