Click here to Skip to main content
13,257,667 members (78,733 online)
Click here to Skip to main content
Add your own
alternative version


60 bookmarked
Posted 11 Jan 2014

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

, 14 Jan 2014
Rate this:
Please Sign up or sign in to vote.
Utilize the database provided by to identify the country of website's visitors based on their ip.


  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 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#) 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;

        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`)


        cmd.CommandText = 
	INFILE '" + file + @"'



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;

            ipLite = new IPLite(cmd);


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

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.


Database TypeConnectionCommandDataAdapter

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


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 -,777,216 -,048,576 -,536

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:


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"];


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) //
        isPublic = false;
    else if (w == 10) // -
        isPublic = false;
    else if (w == 172 && (x >= 16 || x <= 31)) // -
        isPublic = false;
    else if (w == 192 && x == 168) // -
        isPublic = false;

    return isPublic;



Getting IP Number:

Let take this IP address as example:

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 = "";

    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:


SQL Sample: Getting country code from database:

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

Example result:

country_nameUNITED STATES

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;

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


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


This article, along with any associated source code and files, is licensed under The MIT License


About the Author

Software Developer
Malaysia Malaysia
Programming is an art.

You may also be interested in...

Comments and Discussions

Questionupdates with ASP MVC 5 Pin
longnights23-Feb-17 14:54
memberlongnights23-Feb-17 14:54 
SuggestionThe value from GetVisitorIPAddress is unreliable Pin
al13n11-Jan-14 15:03
memberal13n11-Jan-14 15:03 
If the user is behind an internal proxy at their end you will get a private address, not a public one. Only public addresses can be used to determine the country.

Try this:
1. If you first check any x-forwarded-for addresses in order, and take the first that isn't a private address.
2. If no public address found, then check the UserHostAddress for a public address.

If a public address is found then you have what you need to do a country lookup.

FYI: UserHostAddress and REMOTE_ADDR are the same thing, so no need to check both.

Oops, almost forgot, x-forwarded-for is quite unreliable for HTTPS as proxies often don't update the x-forwarded-for chain as they can't read/update the encrypted header. To make things worse, hackers can easily add their own x-forwarded-for header. In short, x-forwarded-for isn't trustworthy, but if you're not making financial decisions based on it, then it's probably good enough.
GeneralRe: The value from GetVisitorIPAddress is unreliable Pin
adriancs11-Jan-14 21:31
memberadriancs11-Jan-14 21:31 
GeneralRe: The value from GetVisitorIPAddress is unreliable Pin
adriancs12-Jan-14 3:16
memberadriancs12-Jan-14 3:16 
GeneralRe: The value from GetVisitorIPAddress is unreliable Pin
al13n12-Jan-14 14:57
memberal13n12-Jan-14 14:57 
GeneralRe: The value from GetVisitorIPAddress is unreliable Pin
adriancs12-Jan-14 16:16
memberadriancs12-Jan-14 16:16 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.171114.1 | Last Updated 14 Jan 2014
Article Copyright 2014 by adriancs
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid