GetHostByAddress Method
Resolves the host name or IP address associated with the specified IP address.
public static System.Net.IPHostEntry GetHostByAddress(string ipAddress)
Parameters
- ipAddress: The IP address to resolve.
Returns
- An IPHostEntry object that contains address information about the host.
Exceptions
ArgumentNullException:ipAddressis null.UnrecognizedIPAddressException:ipAddressis not a valid IP address.SocketException: An error occurred while attempting to access the DNS server.
Remarks
The GetHostByAddress method performs a DNS query to resolve the hostname associated with the provided IP address.
This method is useful for obtaining detailed information about a host, including its host name and aliases, given its IP address.
If the IP address cannot be resolved, a SocketException may be thrown.
Example
using System;
using System.Net;
public class DnsExample
{
public static void Main(string[] args)
{
try
{
string ipAddress = "8.8.8.8"; // Example: Google Public DNS
IPHostEntry hostEntry = Dns.GetHostByAddress(ipAddress);
Console.WriteLine($"Host name for {ipAddress}: {hostEntry.HostName}");
Console.WriteLine("Aliases:");
foreach (string alias in hostEntry.Aliases)
{
Console.WriteLine($"- {alias}");
}
Console.WriteLine("IP Addresses:");
foreach (IPAddress addr in hostEntry.AddressList)
{
Console.WriteLine($"- {addr}");
}
}
catch (ArgumentNullException)
{
Console.WriteLine("IP address cannot be null.");
}
catch (UnrecognizedIPAddressException)
{
Console.WriteLine("The provided string is not a valid IP address.");
}
catch (SocketException ex)
{
Console.WriteLine($"Socket error occurred: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"An unexpected error occurred: {ex.Message}");
}
}
}