Dns Class
Namespace: System.Net
Assembly: System.Net.Primitives (in System.Net.Primitives.dll)
Syntax
public static class Dns
Remarks
The Dns
class provides methods for resolving Domain Name System (DNS) records for a specified host name. This class can resolve the IP address associated with a host name or find all IP addresses associated with a host name. The methods in the Dns
class are asynchronous by default, allowing your application to remain responsive while waiting for DNS resolution to complete.
This class is used to perform DNS lookups, which involve querying DNS servers to translate human-readable domain names (like www.example.com
) into machine-readable IP addresses (like 192.168.1.1
).
Methods
GetHostEntry(string hostNameOrAddress)
Asynchronously resolves a host name or IP address to an IPHostEntry
object.
Syntax
public static Task<IPHostEntry> GetHostEntryAsync(string hostNameOrAddress);
Parameters
hostNameOrAddress
: string
The host name or IP address to resolve.
Returns
A task representing the asynchronous operation. The result of the task is an IPHostEntry
object that contains information about the host.
GetHostAddresses(string hostNameOrAddress)
Asynchronously retrieves the IPAddress
instances that are associated with a host.
Syntax
public static Task<IPAddress[]> GetHostAddressesAsync(string hostNameOrAddress);
Parameters
hostNameOrAddress
: string
The host name or IP address to resolve.
Returns
A task representing the asynchronous operation. The result of the task is an array of IPAddress
objects associated with the host.
Example
The following example demonstrates how to use the GetHostEntryAsync
method to resolve a host name.
using System; using System.Net; using System.Threading.Tasks; public static class DnsExample { public static async Task ResolveHostAsync(string hostName) { try { IPHostEntry hostEntry = await Dns.GetHostEntryAsync(hostName); Console.WriteLine($"Host Name: {hostEntry.HostName}"); Console.WriteLine("IP Addresses:"); foreach (var ipAddress in hostEntry.AddressList) { Console.WriteLine($"- {ipAddress}"); } } catch (Exception ex) { Console.WriteLine($"An error occurred: {ex.Message}"); } } public static async Task Main(string[] args) { await ResolveHostAsync("www.microsoft.com"); } }