Hot File

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

View: 1362    Dowload: 0   Comment: 0   Post by: naruto  
Author: none   Category: PostgreSQL   Fields: Other

0 point/4 review File has been tested

Download   iplite-net-get.zip (3.84 KB)

You need to Sign In to download the file iplite-net-get.zip
If you do not have an account then Sign up for free here

Download error   Report copyright violation

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

Introduction

 

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 Type Connection Command DataAdapter
MSSQL SqlConnection SqlCommand SqlDataAdapter
SQLite SQLiteConnection SQLiteCommand SQLiteDataAdapter
OleDb OleDbConnection OleDbCommand OleDbDataAdapter
PostgreSQL NpgsqlConnection NpgsqlCommand NpgsqlDataAdapter
Firebird FbConnection FbCommand FbDataReader

 

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 range number of addresses
10.0.0.0 - 10.255.255.255 16,777,216
172.16.0.0 - 172.31.255.255 1,048,576
192.168.0.0 - 192.168.255.255 65,536
127.0.0.1 1

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:

Columns Data
ip_from 1089058560
ip_to 1089060863
country_code US
country_name UNITED STATES
region_name MICHIGAN
city_name STERLING HEIGHTS
latitude 42.58031
longitude -83.0302
zip_code 48310
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 />");
    }
}

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

IPLite.NET - Get Country/Region/City From IP Posted on 19-04-2014  Introduction and Setting Up Database Using IPLite.cs Manually Get the Country Information 5/10 1362

Comment:

To comment you must be logged in members.

Files with category

  • Accessing: MySQL Database using MySQL C API

    View: 2447    Download: 2   Comment: 0   Author: none  

    Accessing: MySQL Database using MySQL C API

    Category: PostgreSQL
    Fields: Other

    0.75/6 review
    This article was written for beginners, developers that do not know how to access MySql database using MySQL C API and would like to have a small introduction.

  • Full Database Abstraction Layer Generator

    View: 2533    Download: 0   Comment: 0   Author: none  

    Full Database Abstraction Layer Generator

    Category: PostgreSQL
    Fields: Other

    0/23 review
    This article presents yet another Data Abstraction Layer generator (popular topic). The DAL structure is directly inspired from the DotNetNuke, DAL document and the SQL generation is done using SQLpp. The generator takes care of pretty much...

  • Code .NET 2.0; Build Java; Run Linux

    View: 2043    Download: 0   Comment: 0   Author: none  

    Code .NET 2.0; Build Java; Run Linux

    Category: PostgreSQL
    Fields: Other

    1.5/3 review
    This article is in the Product Showcase section for our sponsors at CodeProject. These reviews are intended to provide you with information on products and services that we consider useful and of value to developers. This is a showcase review for...

  • Postgres Database Backup/Restore From C#

    View: 2951    Download: 2   Comment: 0   Author: none  

    Postgres Database Backup/Restore From C#

    Category: PostgreSQL
    Fields: Other

    0/10 review
    This article provides Postgres database backup/restore functionality. By using this application we can check whether a Postgres database is installed or not in a system. If a Postgres database is installed then the Postgres databases list is...

  • Installing Redmine on Windows in production

    View: 5443    Download: 0   Comment: 0   Author: none  

    Installing Redmine on Windows in production

    Category: PostgreSQL
    Fields: Other

    0/10 review
    This is a very simple step by step guide to install Redmine on Windows server in production. This guide is applicable to IIS 7+ based servers, which include Windows Server 2008, 2008 R2, Windows Vista and Windows 7. Latter two should not be used for...

  • A SQL Management Console for MSSQL 2000 & 2005, MySQL 5.0,...

    View: 3273    Download: 2   Comment: 0   Author: none  

    A SQL Management Console for MSSQL 2000 & 2005, MySQL 5.0,...

    Category: PostgreSQL
    Fields: Other

    0.5625/8 review
    Since MSSQL is not holding the lion share of the market yet, integration/interaction with other RDBMS like PL/Oracle, MySQL, FireBird, DB2, is inevitable. With the class System.Data.Common in ADO .NET 2.0, different data providers can write the...

  • Creating an Interactive Map in ASP.NET 2.0 Using SharpMap

    View: 4377    Download: 5   Comment: 0   Author: none  

    Creating an Interactive Map in ASP.NET 2.0 Using SharpMap

    Category: PostgreSQL
    Fields: Other

    0/2 review
    Showing maps on the web is becoming more and more common. The most well-known ones are Google Maps and Microsoft's Virtual Earth. Creating your own websites with interactive maps require you to get hold on the map-data and convert this data to...

  • DevShot - Database Snapshots for Developers

    View: 956    Download: 0   Comment: 0   Author: none  

    DevShot - Database Snapshots for Developers

    Category: PostgreSQL
    Fields: Other

    0/2 review
    A few weeks back, I got an idea of writing a simple tool for switching database states between coding cycles. I thought this would be a good tool for anyone who is working on database related projects and have to switch between database states since...

 
Newsletter Email

File suggestion for you

File top downloads

logo codetitle
Codetitle.com - library source code to share, download the file to the community
Copyright © 2015. All rights reserved. codetitle.com Develope by Vinagon .Ltd