Click here to Skip to main content
Click here to Skip to main content

How to convert IP address to country name

By , 14 Aug 2008
 

How to retrieve a visitor's IP address

Every visitor to your site or web application has an IP address. It is quite handy to be able to get that address. It can be used for security logging, or perhaps tracing. It can also be used to determine where they are in the world, or at least where their ISP is.

The difficulty is when they are behind a proxy of some sort, and you can only see the IP address of the proxy server. So, here are the code snippets in ASP.NET that first check for an IP addresses that's forwarded from behind a proxy, and if there's none, then just gets the IP address. Here's the same IP retriever with proxy detection in .NET, but in VB.NET:

Dim nowip As String 
nowip = Request.ServerVariables("HTTP_X_FORWARDED_FOR") 
If nowip = "" Then
   nowip = Request.ServerVariables("REMOTE_ADDR")
End If

How do I convert an IP address to an IP number?

IP address (IPV4) is divided into four sub-blocks. Each sub-block has a different weight number, each powered by 256. The IP number is being used in the database because it is efficient to search between a range of numbers in the database.

The beginning IP number and the ending IP number are calculated based on the following formula:

IP Number = 16777216*w + 65536*x + 256*y + z (1)

where:

IP Address = w.x.y.z

For example, if the IP address is "202.186.13.4", then its IP number is "3401190660" based on the above formula.

IP Address = 202.186.13.4
So, w = 202, x = 186, y = 13 and z = 4

IP Number = 16777216*202 + 65536*186 + 256*13 + 4
          = 3388997632 + 12189696 + 3328 + 4
          = 3401190660

To reverse the IP number to the IP address:

w = int ( IP Number / 16777216 ) % 256
x = int ( IP Number / 65536 ) % 256
y = int ( IP Number / 256 ) % 256
z = int ( IP Number ) % 256

where, % is the mod operator and int returns the integer part of the division.

How do I retrieve the country name and the country code from the IP number?

Search the IP-country database to match a unique record that has the IP number that fits between the beginning IP number and the ending IP number.

For example, the IP address "202.186.13.4" is equivalent to the IP number "3401190660". It belongs to the following record in the database because it is between the beginning and the the ending of the IP number:

"3401056256","3401400319","MY","MALAYSIA"

From the recordset, the country name is Malaysia and the country code is MY. Here is a useful link.

How do I use this database

CSV file format

The CSV file contains four fields:

  • Beginning of the IP address range
  • Ending of the IP address range
  • Two-character country code based on ISO 3166
  • Three-character country code based on ISO 3166
  • Country name based on ISO 3166
"0033996344","0033996351","GB","GBR","UNITED KINGDOM"
"0050331648","0083886079","US","USA","UNITED STATES"
"0094585424","0094585439","SE","SWE","SWEDEN"
Field Data Type Field Description
IP_FROM NUMERICAL (DOUBLE) Beginning of the IP address range.
IP_TO NUMERICAL (DOUBLE) Ending of the IP address range.
COUNTRY_CODE2 CHAR(2) Two-character country code based on ISO 3166.
COUNTRY_CODE3 CHAR(3) Three-character country code based on ISO 3166.
COUNTRY_NAME VARCHAR(50) Country name based on ISO 3166

Download CSV database

Convert to Access database

Here is the code-behind:

Partial Class How_to_Convert_IP_Address_Country _
        Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object,_
        ByVal e As System.EventArgs) Handles Me.Load
        Dim nowip As String
        nowip = Request.ServerVariables("HTTP_X_FORWARDED_FOR")
        If nowip = "" Then
            nowip = Request.ServerVariables("REMOTE_ADDR")
        End If

        If txtIPAddress.Text = "" Then
            txtIPAddress.Text = nowip
        End If
        lblError.Text = ""
    End Sub

    Protected Sub Button1_Click(ByVal sender As Object,_
        ByVal e As System.EventArgs) Handles Button1.Click
        On Error GoTo HandleError

        Dim dottedip As String
        Dim Dot2LongIP As Double
        Dim PrevPos As Double
        Dim pos As Double
        Dim num As Double

        dottedip = txtIPAddress.Text

            For i = 1 To 4
                pos = InStr(PrevPos + 1, dottedip, ".", 1)
                If i = 4 Then
                    pos = Len(dottedip) + 1
                End If
                num = Int(Mid(dottedip, PrevPos + 1, pos - PrevPos - 1))
                PrevPos = pos
                Dot2LongIP = ((num Mod 256) * (256 ^ (4 - i))) + Dot2LongIP
            Next

        txtIPNumber.Text = Dot2LongIP

HandleError:
        lblError.Text = Err.Description
    End Sub
End Class

Here is the output:

check-conutry.jpg

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

aspxCode
Web Developer
United States United States
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5mvpKunal_Chowdhury21 Apr '11 - 2:32 
Bookmarked for future reference.
Generala copy of..........memberАslam Iqbal25 Mar '11 - 9:52 
Its a copy of this site:
ip2location[^]
GeneralMy vote of 3membernvijin27 Nov '10 - 23:26 
good
GeneralMy vote of 1memberToddonian15 Dec '09 - 7:44 
The System.Net.IPAddress class provides the functionality needed to convert an IP address to a number. Even if you wanted to do it by hand bit-shift operators should be used, as well as Byte.Parse and String.Split static methods. Almost this entire example can be re-written in one line of code (albeit, a deprecated property):
 
Dim IPNumber As Long = System.Net.IPAddress.Parse("192.168.1.1").Address
GeneralWork perfectly in C#, Thank you!!membermehran_o_net19 Sep '09 - 9:03 
with few changes it work's in C# perfectly too!! Wink | ;)
   String dottedip;
        Double num, Dot2LongIP=0;
        int pos, PrevPos=0;
 
        dottedip = strIPAddress;
            for(int i=1;i<=4;i++) {
                pos = dottedip.ToString().IndexOf(".",PrevPos);
                num = int.Parse(dottedip.Substring(PrevPos, pos - PrevPos));
                PrevPos = pos -1;
                Dot2LongIP = ((num % 256) * ( Math.Pow(256,4 - i))) + Dot2LongIP;
            }

GeneralVB.Net IntergatememberMartin Houstrup17 Aug '09 - 5:22 
Hello I need some help.
I use VB.Net Express 2008 and i have a manual IP Tracker.
So I enter an IP and press track, i t converts the IP to an IP number (works) but i need to know how do i connect the Database into vb and search it through? Please help. I am a newb xD
Questiondoubt with the abovemembersvknair20 Jan '09 - 1:04 
i am uisng vb.net as code behind
tried to use it but got stuck up with a simple query
 
i am uisng the select startemnt in code behind as
 
strqry = "SELECT CountryName FROM ip2country where BeginingIP>=" & IPAddress & " AND EndingIP<=" & IPAddress & ""
 
where ipaddress is the ipno generated
 
how do i use it ???? as this is not working
AnswerRe: doubt with the abovememberdavidberlin10 Mar '09 - 3:43 
if you use MS-SQL, it´s better like this:
 
SELECT CountryName FROM ip2country where @IPAddress between BeginingIP AND EndingIP
GeneralThe world changes and Internet even faster.memberzeek22 Dec '08 - 8:08 
Have read your article, and indeed very nicely done.
I have tried this as well some time ago, but the problem I stumbled on is the fact that the Internet (and the IP allocations) is/are fluid. The database idea is great for fast access and quick results, although I have found that in my case, the data it is already outdated and no longer correct or incomplete within as little as 24 hours, and just gets worse over time.
 
A realtime link to the source, besides a stand alone static one is needed for accuracy, like a link to the controllers of IP assignments. www.arin.net (and it's fellow controllers) or better yet access to IANA.
 
Someone should start a realtime online link service into these databases for the good of all Internet users. There seem to be a few "free" providers, (never used them), but word on the street is that the quality varies = not accurate, incorrect, outdated or not maintained.
 
At present I do a lazy screen scrape off each of the Internet registries as applicable and deal with it later. Not exactly a clean or healthy way, but my data for that request at that time was really correct. (and now for the city name and street name......) Big Grin | :-D
 
If anyone has ideas on how to keep the DB current, please share.
 
Thanks all
 
Jay S
QuestionWhich Country is thismemberkhemant041115 Dec '08 - 20:51 
Hello,
The .csv fileis really very helpful but there r few entries in file such as below
"1052868608","1052871935","RS","",""
"1052871960","1052871975","RS","",""
"1052872001","1052872011","RS","",""
"1052872020","1052872095","RS","",""
"1052872208","1052872235","RS","",""
 
So can any one please tell me what are these entries.
 
Thanks
QuestionDatabase for Ip addressmemberdesigank12 Nov '08 - 20:24 
Hi, This is very useful for me,In my project im getting the startingIPnumber,endingIPnumber,Country,city and Time..I need database for my requirement.Help me if you have any database..
 
Thank You,
Generalnot simple. Use shifts or..memberykorotia17 Oct '08 - 7:42 
System.Net.IPAddress lip = System.Net.IPAddress.Parse(simple.clientip.toString());
// class from long
System.Net.IPAddress lip2 = new System.Net.IPAddress(lip.Address);
 
// string from long
lip2.ToString();
GeneralMe da este error.memberMember 173994428 Aug '08 - 7:32 
Error 53 No se permiten nodos secundarios. (C:\Inetpub\wwwroot\IP-to-Country\web.config line 122)
GeneralVery usefulmemberjsreekumar22 Aug '08 - 12:07 
Cool | :cool:
Well done man!
We are waiting for your next article to identify cities too (Greedy, yeah? Laugh | :laugh: )
Cheers
GeneralCoolmemberashu fouzdar19 Aug '08 - 3:23 
Really useful.
 
dnpro
"Very bad programmer"

GeneralWow!memberAbhilashAshok13 Aug '08 - 20:12 
Its a must have article.
I's looking for this so long.
Thankz
 
Dont think you are no ONE...!!!

GeneralVery nicememberPetros Amiridis11 Aug '08 - 23:00 
Very interesting piece of knowledge! However +1 for finding the City too. Smile | :) ... Aren't we greedy? Smile | :)
GeneralthanksmemberMember 404680211 Aug '08 - 22:47 
Thanks alot.. good job.. WTF | :WTF:
 
Ismail Farajallah
QuestionCity codes too?memberWayne Hetherington11 Aug '08 - 13:01 
Is there any way to extend this further to look up the city name of an IP address? It seems to me that there are quite a number of web site add that somehow find out what city I'm in. I'd love to know how that works.
Good job on this article and the explanation of the calculations.
-W
GeneralInterestingmemberkornakar5 Aug '08 - 20:38 
Very interesting. I've always wondered how they do this Smile | :) Thanks for sharing!

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

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130516.1 | Last Updated 14 Aug 2008
Article Copyright 2008 by aspxCode
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid