Friday, February 26, 2010

How to Check DNS with CSharp?

If you want to know any domain name is matched with certain ip address, you can use System.Net namespace to retrieve IPAddresses collection which is related to domain name. Please check the code snippet written below :
   1:  public static bool CheckDNS(string domain)
   2:  {
   3:      bool result = false;
   4:      try
   5:      {
   6:         IPAddress[] addressList = Dns.GetHostAddresses(domain);
   7:   
   8:         result = addressList.length > 0 ? true : false;
   9:      }
  10:      catch
  11:      {
  12:          result = false;
  13:      }
  14:  }
If  CheckDNS method returns true, it means domain name is related to at least one ip address. If return false, the domain name is not associated to any ip address.

For testing you can pass an existed domain name such as www.technolatte.net and pass a domain name which doesn't exist.

CheckDNS("www.technolatte.net"); //output is true
CheckDNS("www.thisistestdomainname.com"); //output is false