Monday
Oct062008
Whois, DNS, CName, MX record lookup in C#
Monday, October 6, 2008 at 12:40PM This is the source code from the network tools page that use to exist on the previous domain (when the site was hosted on a dedicated server). A good replacement site is who.is, however the source for the tools is below.
The download contains the class library used for the Network Tools and a sample console application. The Whois lookup isn't included, you can grab that from the [Whois article][3]. Most of the credit for tools goes to the NMail server project. The DNS lookup functions were all adapted from that project, such as CNAME, Nameservers and MX records.
The code below shows the simple Hostname to IP and visa versa methods.

using System;
using System.Security;
using System.Net;
using System.Net.Sockets;
namespace Demo
{
public class NetworkUtils
{
/// <summary>
/// Performs a hostname lookup from an IP.
/// </summary>
/// <param name="Ip"></param>
/// <returns></returns>
public static string GetHostnameFromIp(string Ip)
{
string hostname = "";
try
{
IPHostEntry ipHostEntry = Dns.GetHostByAddress(Ip);
hostname = ipHostEntry.HostName;
}
catch ( FormatException )
{
hostname = "Please specify a valid IP address.";
return hostname;
}
catch ( SocketException )
{
hostname = "Unable to perform lookup - a socket error occured.";
return hostname;
}
catch ( SecurityException )
{
hostname = "Unable to perform lookup - permission denied.";
return hostname;
}
catch ( Exception )
{
hostname = "An unspecified error occured.";
return hostname;
}
return hostname;
}
/// <summary>
/// Performs an IP lookup from a hostname.
/// </summary>
/// <param name="Hostname"></param>
/// <returns></returns>
public static string GetIpFromHostname(string Hostname)
{
string ip = "";
try
{
IPHostEntry ipHostEntry = Dns.Resolve(Hostname);
if ( ipHostEntry.AddressList.Length > 0 )
{
//ip = ipHostEntry.AddressList[0].Address.ToString();
ip = ipHostEntry.AddressList[0].ToString();
}
else
{
ip = "No information found.";
}
}
catch ( SocketException )
{
ip = "Unable to perform lookup - a socket error occured.";
return ip;
}
catch ( SecurityException )
{
ip = "Unable to perform lookup - permission denied.";
return ip;
}
catch ( Exception )
{
ip = "An unspecified error occured.";
return ip;
}
return ip;
}
}
}






Reader Comments