Get IP Address from DNS Hostname in C# - Code Example

Resolving Hostnames to IP Addresses in Application Development
When developing applications that interact with TCP/IP networks and the internet, a common requirement arises: the need to translate a hostname into its corresponding IP address. Users generally find hostnames more manageable than numerical IP addresses.
Utilizing the System.Net Namespace
To facilitate this process within your C# code, you must first incorporate the System.Net namespace into your project's using directives.
using System.Net;
Code Example for Hostname Resolution
The following code snippet demonstrates how to retrieve an IP address from a given hostname. It leverages the Dns.GetHostAddresses method.
string howtogeek = "www.howtogeek.com";
IPAddress[] addresslist = Dns.GetHostAddresses(howtogeek);
foreach (IPAddress theaddress in addresslist)
{
Console.WriteLine(theaddress.ToString());
}
This method returns an array of IPAddress objects, as a hostname can potentially resolve to multiple IP addresses.
Verification and Compatibility
The functionality presented here has been successfully tested using the C# 2.0 framework. It remains compatible with later versions of C# as well.
The code iterates through the array of resolved IP addresses, displaying each one to the console.
Successfully resolving a hostname is crucial for establishing network connections and ensuring proper application functionality.