Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

IPLite.NET - Get Country/Region/City From IP

0.00/5 (No votes)
14 Jan 2014 1  
Utilize the database provided by ip2nation.com to identify the country of website's visitors based on their ip.

Contents

  1. Introduction and Setting Up Database
  2. Using IPLite.cs
  3. Manually Get the Country Information


Introduction and Setting Up Database

I would like to share a small class that is written by me, (IPLite.cs). It ultilises database provided by https://lite.ip2location.com to identify the Country, Region and City of website's visitors based on their IP address.

The IP database is updated every month and provides the following data of an IP:

  • Country Code and Name
  • Region
  • City
  • Latitude and Longitude
  • Zip Code
  • Time Zone

Download and restore the database to your server. Personal recommendation is: Restore as another separate dedicated database, don't combine it with your main operating database, but this is up to you to decide.

Sample Database Installation Script for MySQL (C#)

lite.ip2location.com provides the database in two format, BIN and CSV. CSV can be imported directly into MySQL server.

There are two common dump files for MySQL. SQL dump file and CSV dump file.

  • SQL dump file uses normal INSERT to import data
  • CSV uses LOAD DATA

According to documentation of MySQL on Speed of INSERT Statements [^], LOAD DATA is 20 times faster than INSERT. A benchmark [^] had been carried out by Kevin van Zonneveld and presents that LOAD DATA is 2000%++ faster than INSERT.

C# code for importing CSV dump file

string file = "C:\\backupfolder\\IP2LOCATION-LITE-DB11.CSV";
file = file.Replace("\\", "\\\\");

using (MySqlConnection conn = new MySqlConnection(connectionString))
{
    using (MySqlCommand cmd = new MySqlCommand())
    {
        cmd.Connection = conn;
        conn.Open();

        cmd.CommandText =
@"CREATE TABLE `ip2location_db11`(
	`ip_from` INT(10) UNSIGNED,
	`ip_to` INT(10) UNSIGNED,
	`country_code` CHAR(2),
	`country_name` VARCHAR(64),
	`region_name` VARCHAR(128),
	`city_name` VARCHAR(128),
	`latitude` DOUBLE,
	`longitude` DOUBLE,
	`zip_code` VARCHAR(30),
	`time_zone` VARCHAR(8),
	INDEX `idx_ip_from` (`ip_from`),
	INDEX `idx_ip_to` (`ip_to`),
	INDEX `idx_ip_from_to` (`ip_from`, `ip_to`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_bin;";

        cmd.ExecuteNonQuery();

        cmd.CommandText = 
@"LOAD DATA LOCAL
	INFILE '" + file + @"'
INTO TABLE
	`ip2location_db11`
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\r\n'
IGNORE 0 LINES;";

        cmd.ExecuteNonQuery();

        conn.Close();
    }
}

More instructions for setting up other databases (MSSQL, PostgreSQL) are available at their website [^]


Using IPLite.cs

Download IPLite.cs.

The rest of the example in this article will demonstrate by using MySQL.

C# + MySQL sample

private void DisplayCurrentVisitorIpInfo()
{
    IPLite ipLite = null;

    using (MySqlConnection conn = new MySqlConnection(connectionString))
    {
        using (MySqlCommand cmd = new MySqlCommand())
        {
            cmd.Connection = conn;
            conn.Open();

            ipLite = new IPLite(cmd);

            conn.Close();
        }
    }

    Response.Write("<b>REMOTE_ADDR</b><br />");
    WriteInfo(ipLite.REMOTE_ADDR);
}

void WriteInfo(IpInfo ip)
{
    Response.Write("IP Address: " + ip.IpAddress + "<br />");
    Response.Write("IP Number: " + ip.IpNumber + "<br />");
    Response.Write("Country Code: " + ip.CountryCode + "<br />");
    Response.Write("Country: " + ip.CountryName + "<br />");
    Response.Write("Region: " + ip.RegionName + "<br />");
    Response.Write("City: " + ip.CityName + "<br />");
    Response.Write("Latitue: " + ip.Latitude + "<br />");
    Response.Write("Longitue: " + ip.Longitude + "<br />");
    Response.Write("Zip Code: " + ip.ZipCode + "<br />");
    Response.Write("Time Zone: " + ip.TimeZone + "<br />");
    Response.Write("<hr />");
}

Above code shows an example of using MySQL.

For other database, just modify the source and change the object of Connection, Command, DataAdapter to your data provider's respective object/class.

Example:

Database TypeConnectionCommandDataAdapter
MSSQLSqlConnectionSqlCommandSqlDataAdapter
SQLiteSQLiteConnectionSQLiteCommandSQLiteDataAdapter
OleDbOleDbConnectionOleDbCommandOleDbDataAdapter
PostgreSQLNpgsqlConnectionNpgsqlCommandNpgsqlDataAdapter
FirebirdFbConnectionFbCommandFbDataReader

IPLite.cs has 3 classes contain the information for the client's Public IP. They are:

  • REMOTE_ADDR 
  • HTTP_CLIENT_IP
  • HTTP_X_FORWARDED_FOR

In normal case, REMOTE_ADDR will represent the real Public IP for the client. 

If the client uses a proxy server or load balancing server, REMOTE_ADDR might represents the Public IP for the proxy server or load balancing server. Then, we have to refer to HTTP_CLIENT_IP or HTTP_X_FORWARDED_FOR.

If HTTP_CLIENT_IP is detected, it will be the real public IP for him/her. If it is not existed, look for HTTP_X_FORWARDED_FOR.

HTTP_X_FORWARDED_FOR contains a list of IP separated by comma+space. Official format sequence is:

Client IP, Proxy IP 1, Proxy IP 2....

but, unfortunately, not all the manufacturers and operators of proxy server/load balancing server are following this sequence. There are lots of possibilities. However, only one of them is Public IP, else are private IP.

Format of private IP address:

IP address rangenumber of addresses
10.0.0.0 - 10.255.255.25516,777,216
172.16.0.0 - 172.31.255.2551,048,576
192.168.0.0 - 192.168.255.25565,536
127.0.0.11

Loop through all the IPs and locate the IP that is out of the range of private IP.

Now, the bad news, all HTTP_xxxx headers can be easily modified by user. For example, this Firefox Add-On [^] allows users to modify http headers and enables them to use any IP address. However, this happens rarely, only minority of your client might do this. (Normal user won't edit their http headers to trick your website). Besides, if clients are accessing HTTPS protocol's website, proxy servers cannot update the HTTP_X_FORWARDED_FOR chain, this is because the headers are encrypted. Therefore, the only reliable IP for identifying the origin of the client's country is REMOTE_ADDR.

If the accuracy of Region and City is important to you and would like to take 1% of chances to receive fake headers, you may check the client's real public IP by following this sequence:

HTTP_CLIENT_IP  >  HTTP_X_FORWARDED_FOR  >  REMOTE_ADDR

else, just stick to REMOTE_ADDR for retrieving Country info only.

Lastly, if the user is using VPN (Virtual Private Network), even Public IP of REMOTE_ADDR will not able to reflect his/her real origin of Country.


Manually Get the Country Information

Below explains how IPLite.cs works.

First, getting the visitor's IP address by accessing the Server Variables (http headers) of REMOTE_ADDR, HTTP_CLIENT_IP and HTTP_X_FORWARDED_FOR.

Get IP Address from REMOTE_ADDR 

string ipAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

or simply (both return same value in C#) 

string ipAddress = HttpContext.Current.Request.UserHostAddress;

Get IP Address from HTTP_CLIENT_IP

string ipAddress = HttpContext.Current.Request.ServerVariables["HTTP_CLIENT_IP"];

Get IP Address from HTTP_X_FORWARDED_FOR

public string GetIPFromHttpXForwardedFor()
{
    string ipList = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
    string[] ipArray = ipList.Split(',');

    foreach (string ipAddress in ipArray)
    {
        if (IsPublicIP(ipAddress.Trim()))
            return ipAddress;
    }

    return null;
}

private bool IsPublicIP(string IpAddress)
{
    bool isPublic = true;

    string[] ips = IpAddress.Split('.');
    int w = int.Parse(ips[0]);
    int x = int.Parse(ips[1]);
    int y = int.Parse(ips[2]);
    int z = int.Parse(ips[3]);

    if (w == 127 && x == 0 && y == 0 && z == 1) // 127.0.0.1
    {
        isPublic = false;
    }
    else if (w == 10) // 10.0.0.0 - 10.255.255.255
    {
        isPublic = false;
    }
    else if (w == 172 && (x >= 16 || x <= 31)) // 172.16.0.0 - 172.31.255.255
    {
        isPublic = false;
    }
    else if (w == 192 && x == 168) // 192.168.0.0 - 192.168.255.255
    {
        isPublic = false;
    }

    return isPublic;
}

 

continue...

Getting IP Number:

Let take this IP address as example:

64.233.191.255

Format of IP Address: W.X.Y.Z

IP Number Calculation Format

= 16777216*W + 65536*X + 256*Y + (1)Z

C# Code

public static long GetIPNumber(string ipAddress)
{
    if (ipAddress == "::1")
        ipAddress = "127.0.0.1";

    string[] ips = ipAddress.Split('.');

    long w = long.Parse(ips[0]) * 16777216;
    long x = long.Parse(ips[1]) * 65536;
    long y = long.Parse(ips[2]) * 256;
    long z = long.Parse(ips[3]);

    long ipnumber = w + x + y + z;
    return ipnumber;
}

Example result:

1089060863

SQL Sample: Getting country code from database:

select * from ip2location_db11 where ip_from <= 1089060863 and ip_to >= 1089060863 limit 0,1;

Example result:

ColumnsData
ip_from1089058560
ip_to1089060863
country_codeUS
country_nameUNITED STATES
region_nameMICHIGAN
city_nameSTERLING HEIGHTS
latitude42.58031
longitude-83.0302
zip_code48310
time_zone-05:00

C# + MySQL sample code

private void GetData()
{
    int ipNumber = 1089060863;
    DataTable dt = new DataTable();

    using (MySqlConnection conn = new MySqlConnection(connectionString))
    {
        using (MySqlCommand cmd = new MySqlCommand())
        {
            cmd.Connection = conn;
            conn.Open();

            cmd.CommandText = @"select * from ip2location_db11 where 
                                ip_from <= " + ipNumber + @" and
                                ip_to >= " + ipNumber + " limit 0,1;";
            MySqlDataAdapter da = new MySqlDataAdapter(cmd);
            da.Fill(dt);

            conn.Close();
        }
    }

    foreach (DataColumn dc in dt.Columns)
    {
        string col = dc.ColumnName;
        Response.Write(col + ": " + dt.Rows[0][col] + "<br />");
    }
}

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