Wednesday, November 24, 2010

DNS Classes in C#

The System.Net namespace contains the Dns class, which provides all the necessary DNS functions for C# programs. This section describes the Dns class methods and shows how they can be used in C# programs to utilize the DNS capabilities of the system.

Synchronous Methods

There are four synchronous methods defined in the Dns class:
  • GetHostName()
  • GetHostByName()
  • GetHostByAddress()
  • Resolve()

GetHostName()

The GetHostName() method is used to determine the hostname of the local system the program is running on. This information is frequently needed for network programs, so you’ll see this method used a lot. The format is simple: there are no parameters to enter, and the result is a string object:
string hostname = Dns.GetHostName();
The information retrieved by GetHostName()hostname should be the same name that appears in the Registry Hostname data value, along with the Domain data value, to create the complete fully-qualified domain name (FQDN) of the system. The FQDN includes the local hostname, along with the full domain name information.

GetHostByName()

The GetHostByName() method performs a DNS query for a specified hostname using the default DNS server configured on the system. The format of the method is as follows:
IPHostEntry GetHostByName(string hostname)
The IPHostEntry that is returned by GetHostByName() is itself an interesting object. It associates a DNS hostname with an array of alias names and IP addresses. It contains three properties:
  • AddressList: An array of IPAddress objects, one for each assigned IP address
  • Aliases: An array of string objects, one for each alias
  • HostName: A string object for the hostname
The AddressList and Aliases objects must be separated into their individual array elements in order to retrieve the information stored. This is often done using the foreach function in C#. 

No comments:

Post a Comment