Dns Class

System.Net

Provides services for resolving domain names and IP addresses. This class contains methods that can be used to perform DNS (Domain Name System) lookups to translate hostnames into IP addresses and vice versa.

Methods

public IPHostEntry GetHostEntry( string hostNameOrAddress )
Resolves a hostname or IP address to an IPHostEntry object. This method performs a synchronous DNS lookup.
public static async Task<IPHostEntry> GetHostEntryAsync( string hostNameOrAddress )
Resolves a hostname or IP address to an IPHostEntry object asynchronously. This method is suitable for use in asynchronous operations to avoid blocking the calling thread.
public static string GetHostName()
Retrieves the fully qualified domain name of the local computer.
public static IPAddress[] GetHostAddresses( string hostNameOrAddress )
Retrieves the IP addresses for a specified hostname or IP address. This method can return IPv4 and IPv6 addresses.
public static async Task<IPAddress[]> GetHostAddressesAsync( string hostNameOrAddress )
Retrieves the IP addresses for a specified hostname or IP address asynchronously.

Example Usage


using System;
using System.Net;

public class DnsExample
{
    public static void Main(string[] args)
    {
        try
        {
            // Resolve a hostname to IP addresses
            string hostName = "www.microsoft.com";
            IPHostEntry hostInfo = Dns.GetHostEntry(hostName);

            Console.WriteLine($"Hostname: {hostInfo.HostName}");
            Console.WriteLine("IP Addresses:");
            foreach (IPAddress ip in hostInfo.AddressList)
            {
                Console.WriteLine($"- {ip}");
            }

            // Get the local machine's hostname
            string localHostName = Dns.GetHostName();
            Console.WriteLine($"\nLocal Hostname: {localHostName}");

        }
        catch (SocketException e)
        {
            Console.WriteLine($"SocketException caught: {e.Message}");
        }
        catch (ArgumentException e)
        {
            Console.WriteLine($"ArgumentException caught: {e.Message}");
        }
    }
}
            

Related Classes