Click here to Skip to main content
15,897,273 members
Articles / Programming Languages / C#

Extreme Optimization #1.1: Mapping IP addresses to country codes.

Rate me:
Please Sign up or sign in to vote.
4.81/5 (34 votes)
30 May 200310 min read 122.2K   2.9K   70  
Highly optimized classes for looking up the country code corresponding to an IP address
// Copyright � 2003 by Jeffrey Sax
// All rights reserved.
// http://www.extremeoptimization.com/
// Filename: Test.cs
// Last modified: May 28, 2003.

using System;
using System.Collections;
using System.IO;
using System.Net;

namespace Extreme.IPCountryLookup
{
	/// <summary>
	/// Summary description for Class1.
	/// </summary>
	class Test
	{
		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main(string[] args)
		{
			Int32 indexLength;
			if (args.Length < 1)
				indexLength = 16;
			else
				indexLength = Int32.Parse(args[0]);
			//ITCTest(1);
			//ITCTest(8);
			//ITCTest(12);
			ITCTest(indexLength);
			ITCTest2();
			Console.ReadLine();
		}
		/// <summary>
		/// This function lets you look up manually entered IP addresses.
		/// The function exits when you enter an empty line.
		/// </summary>
		public static void MyTest()
		{
			String host;
			Console.WriteLine("Enter host name or IP address:");
			while ((host = Console.ReadLine()).Length > 1)
			{
				try
				{
					TestIPCountryLookup(host);
				}
				catch (Exception e)
				{
					Console.Write("Error: ");
					Console.WriteLine(e.Message);
				}
			}
		}
		

		public static ArrayList LoadIpList(string name)
		{
			ArrayList result = new ArrayList(10000);

			FileStream fs = new FileStream(name, FileMode.Open);
			StreamReader sr = new StreamReader(fs);

			string line;

			while ((line = sr.ReadLine()) != null)
			{
				result.Add(line);
			}

			sr.Close();
			fs.Close();
	    
			return result;
		}

		static IPCountryTable table;

		public static void ITCTest(Int32 indexLength)
		{
			long initialmemory = GC.GetTotalMemory(true);
			Extreme.HiResTimer timer = new Extreme.HiResTimer();

			timer.Reset();
			timer.Start();
			table = new IPCountryTable(indexLength);
			table.LoadStatisticsFile(@"..\..\resources\ripencc.latest", true);
			table.LoadStatisticsFile(@"..\..\resources\arin.latest", true);
			table.LoadStatisticsFile(@"..\..\resources\apnic.latest", false);
			table.LoadStatisticsFile(@"..\..\resources\lacnic.latest", true);
			timer.Stop();
			Single dataLoadTime = timer.ElapsedSeconds;
			GC.Collect();
			GC.WaitForPendingFinalizers();
			long afterloadmemory = GC.GetTotalMemory(true);

			timer.Reset();
			timer.Start();
			ArrayList ips = LoadIpList(@"..\..\iplist.txt");
			timer.Stop();
			Single sampleLoadTime = timer.ElapsedSeconds;

			Console.WriteLine("Max memory taken by the tables: {0}KB", (afterloadmemory - initialmemory)/1024);
			Console.WriteLine("IP tables loaded in {0} ({1} networks)", dataLoadTime, table.NetworkCodeCount );
			Console.WriteLine("IP list loaded in {0} ({1} ip addresses)", 
				sampleLoadTime, 
				ips.Count);

			Console.WriteLine("Testing ip look-up speed...");

			timer.Reset();
			timer.Start();
			Int32 count = ips.Count;
			for (Int32 iteration = 0; iteration < 10; iteration++)
				foreach(String ip in ips)
					table.GetCountry(ip);
			timer.Stop();
			Single lookupTime = timer.ElapsedSeconds;

			Console.WriteLine("{0} addresses were translated in {1}s ({2} ip/s)", 
				ips.Count,  lookupTime,
				10 * (int)(ips.Count / lookupTime) );
			Console.WriteLine("Duration: {0}", lookupTime);

			Console.WriteLine("Country code for 195.149.21.72: {0}", table.GetCountry("195.149.21.72"));
			Console.WriteLine("Country code for 81.3.59.134: {0}", table.GetCountry("81.3.59.134"));
			Console.WriteLine("Country code for 194.134.233.72: {0}", table.GetCountry("194.134.233.72"));
		}

		/// <summary>
		/// A short test of several known IP - country code combinations.
		/// </summary>
		public static void ITCTest2()
		{
			Console.WriteLine("217.224.0.0 = {0}", table.GetCountry("217.224.0.0"));
			Console.WriteLine("217.224.133.25 = {0}", table.GetCountry("217.224.133.25"));

			Console.WriteLine("217.208.23.45 = {0} (SE)", table.GetCountry("217.208.23.45"));
			Console.WriteLine("195.96.96.111 = {0} (NL)", table.GetCountry("195.96.96.111"));
			Console.WriteLine("81.16.128.23 = {0} (RU)", table.GetCountry("81.16.128.23"));
			Console.WriteLine("62.4.160.87 = {0} (BE)", table.GetCountry("62.4.160.87"));
			// The following line mistakenly listed the country as 'ICI'
			Console.WriteLine("81.50.140.32 = {0} (FR)", table.GetCountry("81.50.140.32"));
			Console.WriteLine("81.70.12.45 = {0} (NL)", table.GetCountry("81.70.12.45"));
			Console.WriteLine("81.88.95.45 = {0} (KZ)", table.GetCountry("81.88.95.45"));
		}

		/// <summary>
		/// Looks up the country code for a host name or IP address.
		/// </summary>
		/// <param name="hostName">A <see cref="String"/> value
		/// containing the host name or IP address.</param>
		/// <remarks>If the first character of <paramref cref="hostName" />
		/// is not numerical, it is considered a domain name, and
		/// it is resolved using the .NET framework's built-in
		/// DNS lookup method.</remarks>
		static private void TestIPCountryLookup(String hostName)
		{
			IPAddress ip;

			if (hostName[0] > '9')
				ip = System.Net.Dns.Resolve(hostName).AddressList[0];
			else
				ip = IPAddress.Parse(hostName);

			String result = table.GetCountry(ip.ToString());
			Console.Write(" (");
			Console.Write(ip.ToString());
			Console.Write(") -> ");
			Console.WriteLine(result);
		}
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Founder Extreme Optimization
Canada Canada
Jeffrey has been writing numerical software for many years. He is founder and president of Extreme Optimization, a Toronto based provider of numerical component libraries for the .NET framework. He loves challenges, especially when it comes to making code run fast, and finding simplicity and elegance in what looks like complicated chaos.

Comments and Discussions