Skip to main content

C# method to resolve the DNS hostname from an IP address.

public string GetHostName(string ipAddress)
{
    if (string.IsNullOrEmpty(ipAddress))
        return null;

    try
    {
        System.Net.IPHostEntry entry = System.Net.Dns.GetHostEntry(ipAddress);
        if (entry != null)
            return entry.HostName;
    }
    catch (System.Net.Sockets.SocketException ex)
    {
        System.Diagnostics.Debug.WriteLine(
            "unknown host {0} - {1}", ipAddress, ex.Message
        );
    }

    return null;
}

// Usage:

void Main()
{
    var ipAddress = "170.229.128.146";

    Console.WriteLine("IP ......: {0} {1} DNS ...: {2}",
        ipAddress, Environment.NewLine, GetHostName(ipAddress)
    );
}