Class System.Net.Dns

Provides access to the Domain Name System (DNS) name resolution service.

Summary

The System.Net.Dns class provides methods for performing DNS lookups and other DNS-related operations. It allows you to resolve hostnames to IP addresses, get canonical hostnames, and resolve IP addresses to hostnames.

This class is part of the System.Net namespace and is essential for network programming that requires communication between machines using domain names.

Members

Methods

Properties

This class does not expose any public static properties.

Fields

This class does not expose any public static fields.

Remarks

The Dns class provides a high-level interface for DNS operations. For lower-level control over DNS queries, consider using classes within the System.Net.Sockets namespace.

When resolving hostnames, it's important to handle potential exceptions, such as SocketException, which can occur if the DNS server is unreachable or the hostname cannot be resolved.

The asynchronous methods (BeginGetHostAddresses, EndGetHostAddresses, BeginGetHostEntry, EndGetHostEntry) are recommended for applications that need to remain responsive during network operations.

Example Usage

The following example demonstrates how to resolve a hostname to its IP addresses and get the host entry:

using System;
using System.Net;

public class DnsExample
{
    public static void Main(string[] args)
    {
        string hostname = "www.example.com";

        try
        {
            // Resolve hostname to IP addresses
            IPAddress[] addresses = Dns.GetHostAddresses(hostname);
            Console.WriteLine($"IP Addresses for {hostname}:");
            foreach (IPAddress address in addresses)
            {
                Console.WriteLine($"- {address}");
            }

            // Get the host entry
            IPHostEntry hostEntry = Dns.GetHostEntry(hostname);
            Console.WriteLine($"\nHost Entry for {hostname}:");
            Console.WriteLine($"  Host Name: {hostEntry.HostName}");
            Console.WriteLine($"  Aliases: {string.Join(", ", hostEntry.Aliases)}");
            Console.WriteLine($"  IP Addresses:");
            foreach (IPAddress address in hostEntry.AddressList)
            {
                Console.WriteLine($"  - {address}");
            }

            // Get local hostname
            string localHostname = Dns.GetHostName();
            Console.WriteLine($"\nLocal Hostname: {localHostname}");
        }
        catch (SocketException ex)
        {
            Console.WriteLine($"SocketException caught: {ex.Message}");
        }
        catch (ArgumentException ex)
        {
            Console.WriteLine($"ArgumentException caught: {ex.Message}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An unexpected error occurred: {ex.Message}");
        }
    }
}