Simple Tool to find the country of an IP address

Introduction

Sometimes, it is convenient to know where are located your web page readers or your email senders. But the only thing you know about them is their IP address. The purpose of this tool is to map an IP address to a country name by using IP databases freely available on the internet.

Databases

I found 2 databases, with quite the same internal, that can be used for this purpose. They are available in CSV format which is a text format :

With internal format:

  ipFrom, ipTo, Country2, Country3, countryName
ex:
"201674096","201674111","CA","CAN","CANADA"

With internal format:

  ipFrom, ipTo, Registry, Date, Country2, Country3, countryName
ex:
"405921792","405929983","arin","1225411200","CA","CAN","Canada"

In the csv file, IP are resented as a decimal representation of a 32 bits binary number.

These databases are in constant updating. It may be necessary to download one of them from time to time.

IP affresses are allocated as a range starting at ipFrom and ending at ipTo, and one per line. The database contains close to 100 000 IP ranges.

How the database is used

Csv format is convenient for transfering data but less for be used by a program. So the first thing the program will do is to create to 2 tables in 2 files ip.db and country.db from the csv file. The csv file can be simple text (not compressed) or compressed with gzip. When these 2 files are created, the csv file is no longer necessary. Installing a csv file, newer than the db files, will make the program to recreate them.

As we can see, the db files do not take more room than the compressed csv file.

-rw-rw-r-- 1 hq hq   32768 2009-05-28 09:37 country.db
-rw-rw-r-- 1 hq hq 1148592 2009-05-28 09:37 ip.db
-rw-rw-r-- 1 hq hq 1086984 2009-05-28 09:33 ipToCountry.gz

Implementation

A library file tsdb.c do the most of the job. The following is an example of how an application can interface to the library.

   TsDb *db = tsdb_new( gcsvFile, gipFile, gcoFile );
...
   if ( tsdb_find_country( db, myip) ) {
      ...
   }
...
tsdb_destroy(db);

Two example applications are provided testdb and webip2co. testdb is a test program and can be used to search an IP, dump the database, dump country table, add a record.

[hq@olix db]$ testdb 193.49.148.26
"3241251866", 193.49.148.26
"3241148416","3241410559","FR","FRA","France"
[hq@olix db]$ testdb -i 193.49.148.26
"3241251866", 193.49.148.26
"193.48.0.0","193.51.255.255","FR","FRA","France"
[hq@olix db]$ testdb -i 3241251866
"3241251866", 193.49.148.26
"193.48.0.0","193.51.255.255","FR","FRA","France"

webip2co, when given an IP address, is used to update a visitors file like you can see in this page.

Download

License

This software is licensed under the terms of the GNU General Public License as published by the Free Software Foundation.