The Socket class in the System.Net.Sockets namespace is used
for working with Sockets in C#. Note that there is a local and also a remote
end point associated with each socket. We will learn more on this class later
in the article.
The System.Net namespace class contains an important class
called Dns that can be used to access DNS (Domain Naming Service). Well, what
is a DNS, anyway? Domain Naming Service or DNS is a naming service that is used
to name the nodes over a network for simplicity reasons. The domain name is
actually a textual name that identifies a host in a network. The DNS servers
have the DNS names stored along with their corresponding IP addresses. The
Wikipedia states, "The Domain Name system (DNS) associates various sorts
of information with so-called domain names; most importantly, it serves as the
"phone book" for the Internet by translating human-readable computer
hostnames, e.g. www.example.com, into the IP addresses, e.g. 208.77.188.166,
that networking equipment needs to deliver information. It also stores other
information such as the list of mail exchange servers that accept email for a
given domain. In providing a worldwide keyword-based redirection service, the
Domain Name System is an essential component of contemporary Internet use."
Now, in order to retrieve the host name of your local
system, use the following:
Listing 1
Console.WriteLine("The host name of the local computer is: " + Dns.GetHostName());
The host name of the local computer is displayed as shown in
the figure below.
Figure 1
In the above code snippet, GetHostName() is a static method
of the Dns class. Here is a simple program that illustrates how you can display
the IP address of the www.hotmail.com web
site using this class.
Listing 2: Displaying the IP address of Hotmail
using Sockets
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace TestSocket
{
class Program
{
static void Main(string[]args)
{
try
{
IPHostEntry IPHost = Dns.GetHostEntry("www.hotmail.com");
IPAddress[]ipAddress = IPHost.AddressList;
StringBuilder strIpAddress = new StringBuilder();
for (int i = 0; i < ipAddress.Length; i++)
{
strIpAddress.Append(ipAddress[i].ToString());
}
Console.WriteLine("The IP Address is: " + strIpAddress.ToString());
}
catch (SocketException ex)
{
Console.WriteLine("Error Occured! " + ex);
}
Console.Read();
}
}
}
When you execute the above program, the IP address of www.hotmail.com. In this case it displayed as
211.206.123.219. However, if you are not connected to the network, the method
fails and a SocketException is thrown. The exception is caught in the catch
block shown in the above program. The figures below illustrate the output in
each case.
Figure 2
Figure 3: The message for the SocketException
thrown when not connected