System.Net.Dns.GetHostByName Method
System.Net.Dns.GetHostEntry instead.
Retrieves host information corresponding to the specified host name from the Domain Name System (DNS) database.
Syntax
Parameters
hostName: The name of the host to resolve.
Return Value
An IPHostEntry object that contains address information for the host.
Exceptions
SocketException: An error occurred while attempting to resolvehostName.ArgumentNullException:hostNameis null.
Remarks
The GetHostByName method is an older way to perform DNS lookups and is available for compatibility with earlier versions of the .NET Framework. It has been superseded by the more robust and flexible GetHostEntry method.
When you call GetHostByName, the .NET Framework performs a DNS query to resolve the provided host name into an IP address. The result is returned as an IPHostEntry object, which contains properties such as:
HostName: The canonical name of the host.Aliases: An array of aliases for the host.AddressList: An array ofIPAddressobjects for the host.
Note: This method may return unexpected results or fail for IPv6 addresses. It is strongly recommended to use System.Net.Dns.GetHostEntry for all new development.
Example
The following example demonstrates how to use the deprecated GetHostByName method to retrieve information for a given host. (For demonstration purposes only; use GetHostEntry in production code.)
using System;
using System.Net;
public class DnsExample
{
public static void Main(string[] args)
{
string hostNameToResolve = "www.example.com";
try
{
// Use the deprecated method for demonstration
IPHostEntry ipHostInfo = Dns.GetHostByName(hostNameToResolve);
Console.WriteLine($"Host Name: {ipHostInfo.HostName}");
Console.WriteLine("Aliases:");
if (ipHostInfo.Aliases != null && ipHostInfo.Aliases.Length > 0)
{
foreach (string alias in ipHostInfo.Aliases)
{
Console.WriteLine($" - {alias}");
}
}
else
{
Console.WriteLine(" (No aliases found)");
}
Console.WriteLine("IP Addresses:");
if (ipHostInfo.AddressList != null && ipHostInfo.AddressList.Length > 0)
{
foreach (IPAddress ipAddress in ipHostInfo.AddressList)
{
Console.WriteLine($" - {ipAddress}");
}
}
else
{
Console.WriteLine(" (No IP addresses found)");
}
}
catch (SocketException ex)
{
Console.WriteLine($"Error resolving host '{hostNameToResolve}': {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"An unexpected error occurred: {ex.Message}");
}
}
}