Introduction
The code used in this article allows you to resolve a hostname in C# correctly with proper error handling and returns a IPv4 address.
Background
There is a high probability of getting errors while resolving a host name in C#. There is no clear way to know whether the IP was resolved or
not unless the Exceptions are handled correctly, Moreover when the Host is resolved you will get an IP list which can include both IP version 4 and IP version
6 addresses. The below Method is a workaround that can be used validate whether the host name was resolved correctly and then to obtain the version 4 IP address.
Using the code
Simply you can add this method to your code file and use it you will have to import the below libraries.
using System.Net;
using System.Net.Sockets;
public static bool GetResolvedConnecionIPAddress(string serverNameOrURL,
out IPAddress resolvedIPAddress)
{
bool isResolved = false;
IPHostEntry hostEntry = null;
IPAddress resolvIP = null;
try
{
if (!IPAddress.TryParse(serverNameOrURL, out resolvIP))
{
hostEntry = Dns.GetHostEntry(serverNameOrURL);
if (hostEntry != null && hostEntry.AddressList != null
&& hostEntry.AddressList.Length > 0)
{
if (hostEntry.AddressList.Length == 1)
{
resolvIP = hostEntry.AddressList[0];
isResolved = true;
}
else
{
foreach (IPAddress var in hostEntry.AddressList)
{
if (var.AddressFamily == AddressFamily.InterNetwork)
{
resolvIP = var;
isResolved = true;
break;
}
}
}
}
}
else
{
isResolved = true;
}
}
catch (Exception ex)
{
isResolved = false;
resolvIP=null;
}
finally
{
resolvedIPAddress = resolvIP;
}
return isResolved;
}
IPAddress ip = null;
if (GetResolvedConnecionIPAddress("testDomain.com", out ip))
{
}
Points of Interest
This is well tested solution when it comes to resolving host name.