C#使用Dns类实现查询主机名对应IP地址

  using System;

  using System.Threading.Tasks;

  using System.Net;

  namespace DnsLookup

  {

  class Program

  {

  ///

  /// 样例应用程序实现一个控制台程序(包),要求用户输入主机名(也可以添加一个IP地址),

  /// 通过Dns.GetHostEntryAsync得到一个IPHostEntry。在IPHostEntry中,使用AddressList属性访问地址列表。

  /// 主机的所有地址以及AddressFamily都写入控制台。

  ///

  ///

  ///

  ///

  static async Task Main(string[] args)

  {

  do

  {

  Console.Write("Hostname: ");

  string hostname = Console.ReadLine();

  if (hostname.CompareTo("exit") == 0)

  {

  Console.WriteLine("bye!");

  return;

  }

  await OnLookupAsync(hostname);

  Console.WriteLine();

  } while (true);

  }

  public static async Task OnLookupAsync(string hostname)

  {

  try

  {

  IPHostEntry ipHost = await Dns.GetHostEntryAsync(hostname);

  Console.WriteLine($"Hostname: {ipHost.HostName}");

  foreach (IPAddress address in ipHost.AddressList)

  {

  Console.WriteLine($"Address Family: {address.AddressFamily}");

  Console.WriteLine($"Address: {address}");

  }

  }

  catch (Exception ex)

  {

  Console.WriteLine(ex.Message);

  }

  }

  }

  }