MSDN Library

System.Net.Dns Class

Namespace: System.Net

Provides name resolution functionality.

The System.Net.Dns class provides methods for translating host names to IP addresses and IP addresses to host names. It acts as a wrapper around the underlying operating system's name resolution services.

Methods

Properties

Remarks

The Dns class provides a simplified interface to the underlying operating system's name resolution mechanisms, such as DNS, WINS, and the local hosts file. It abstracts away the complexities of these services, allowing developers to easily translate between host names and IP addresses.

When resolving a host name, the Dns class might query multiple name resolution services in a specific order defined by the operating system. The results from these services are aggregated, and a single IPHostEntry object is returned.

For asynchronous operations, the Dns class supports the .NET asynchronous programming model using IAsyncResult. Modern .NET applications should favor the async/await pattern with the GetHostEntryAsync and GetHostAddressesAsync methods.

Example


using System;
using System.Net;

public class DnsExample
{
    public static void Main(string[] args)
    {
        try
        {
            // Resolve a host name to an IP address
            string hostName = "www.microsoft.com";
            IPHostEntry ipHostEntry = Dns.GetHostEntry(hostName);

            Console.WriteLine($"Host Name: {ipHostEntry.HostName}");

            Console.WriteLine("IP Addresses:");
            foreach (IPAddress ipAddress in ipHostEntry.AddressList)
            {
                Console.WriteLine($"- {ipAddress}");
            }

            // Get the local host name
            string localHostName = Dns.GetHostName();
            Console.WriteLine($"\nLocal Host Name: {localHostName}");
        }
        catch (SocketException ex)
        {
            Console.WriteLine($"SocketException caught: {ex.Message}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred: {ex.Message}");
        }
    }
}