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.
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}");
}
}
}