System.Net.Dns.GetHostByName Method

This method is obsolete. Use System.Net.Dns.GetHostEntry instead.

Retrieves host information corresponding to the specified host name from the Domain Name System (DNS) database.

Syntax

public static IPHostEntry GetHostByName( string hostName );

Parameters

Return Value

An IPHostEntry object that contains address information for the host.

Exceptions

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:

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}");
        }
    }
}
            

See Also