Network tools source

The source code for the network tools page.

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. 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 Sloppycode
{
    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;
    	}
    }
}
Last updated on 03 March 2009

Comments

blog comments powered by Disqus