Chris's coding blog

Whois, DNS, CName, MX record lookup in C#

October 06, 2008

Download

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 post. 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.

Network tools console

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;
}
}
}
view raw gistfile1.cs hosted with ❤ by GitHub

csharp

I'm Chris Small, a software engineer working in London. This is my tech blog. Find out more about me via GithubStackoverflowResume