Click here to Skip to main content
15,896,154 members
Articles / Web Development / ASP.NET

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

Rate me:
Please Sign up or sign in to vote.
4.73/5 (11 votes)
14 Jan 2014MIT4 min read 74.7K   2.1K   60  
Utilize the database provided by ip2nation.com to identify the country of website's visitors based on their ip.
using System;
using System.Web;
using System.Collections.Generic;
using System.Text;
using MySql.Data.MySqlClient;
using System.Data;
using System.Net;

namespace System
{
    public class Ip2Nation
    {
        public IpInfo REMOTE_ADDR = new IpInfo();
        public IpInfo HTTP_CLIENT_IP = new IpInfo();
        public List<IpInfo> HTTP_X_FORWARDED_FOR = new List<IpInfo>();

        public static long ConvertIPAddressToNumber(string ip)
        {
            try
            {
                string[] ips = ip.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;
            }
            catch
            {
                return -1;
            }
        }

        public Ip2Nation()
        { }

        public Ip2Nation(MySqlCommand cmd)
        {
            GetData(cmd);
        }

        public void GetData(MySqlCommand cmd)
        {
            string ipList = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

            if (ipList != null)
            {
                string[] ipArray = ipList.Split(',');

                HTTP_X_FORWARDED_FOR = new List<IpInfo>();
                foreach (string ip in ipArray)
                {
                    HTTP_X_FORWARDED_FOR.Add(new IpInfo(cmd, ip.Trim()));
                }
            }

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

            REMOTE_ADDR = new IpInfo(cmd, ipRemoteAddr.Trim());

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

            if (ipClientIp != null)
            {
                HTTP_CLIENT_IP = new IpInfo(cmd, ipClientIp.Trim());
            }
        }
    }

    public class IpInfo
    {
        public string IpAddress = "";
        public long IpNumber = 0;
        public string Code = "";
        public string IsoCode2 = "";
        public string IsoCode3 = "";
        public string Country = "";
        public string IsoCountry = "";
        public string Latitude = "";
        public string Longtitude = "";

        public IpInfo()
        { }

        public IpInfo(MySqlCommand cmd, string ipAddress)
        {
            IpAddress = ipAddress;

            IpNumber = Ip2Nation.ConvertIPAddressToNumber(ipAddress);

            if (IpNumber == -1)
            {
                InvalidIPAddress();
                return;
            }

            if (!IsPrivateNetwork())
                GetData(cmd);
        }

        void InvalidIPAddress()
        {
            Code = "";
            IsoCode2 = "";
            IsoCode3 = "";
            Country = "Invalid IP Address";
            IsoCountry = "Invalid IP Address";
            Latitude = "";
            Longtitude = "";
        }

        bool IsPrivateNetwork()
        {
            bool isPN = false;

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

            // Private Network
            // http://en.wikipedia.org/wiki/Private_network

            if (w == 127 && x == 0 && y == 0 && z == 1) // 127.0.0.1
            {
                isPN = true;

                Country = "Localhost";
                IsoCountry = "Localhost";
            }
            else if (w == 10) // 10.0.0.0 - 10.255.255.255
            {
                isPN = true;

                Country = "Private Network";
                IsoCountry = "Private Network";
            }
            else if (w == 172 && (x >= 16 || x <= 31)) // 172.16.0.0 - 172.31.255.255
            {
                isPN = true;

                Country = "Private Network";
                IsoCountry = "Private Network";
            }
            else if (w == 192 && x == 168) // 192.168.0.0 - 192.168.255.255
            {
                isPN = true;

                Country = "Private Network";
                IsoCountry = "Private Network";
            }

            if (isPN)
            {
                isPN = true;

                Code = "";
                IsoCode2 = "";
                IsoCode3 = "";
                Latitude = "";
                Longtitude = "";
            }

            return isPN;
        }

        private void GetData(MySqlCommand cmd)
        {
            cmd.CommandText = string.Format("select b.* from ip2nation a inner join ip2nationcountries b on a.country = b.code where a.ip <= {0} order by a.ip desc limit 0,1;", IpNumber);
            DataTable dt = new DataTable();
            using (MySqlDataAdapter da = new MySqlDataAdapter(cmd))
            {
                da.Fill(dt);
            }

            if (dt.Rows.Count == 0)
            {
                Code = "";
                IsoCode2 = "";
                IsoCode3 = "";
                Country = "Record Not Found.";
                IsoCountry = "Record Not Found.";
                Latitude = "0";
                Longtitude = "0";
                return;
            }

            DataRow dr = dt.Rows[0];

            Code = dr["code"] + "";
            IsoCode2 = dr["iso_code_2"] + "";
            IsoCode3 = dr["iso_code_3"] + "";
            Country = dr["country"] + "";
            IsoCountry = dr["iso_country"] + "";
            Latitude = dr["lat"] + "";
            Longtitude = dr["lon"] + "";
        }
    }
}

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, along with any associated source code and files, is licensed under The MIT License


Written By
Software Developer
Other Other
Programming is an art.

Comments and Discussions