本文转自:http://www.codeproject.com/Articles/28363/How-to-convert-IP-address-to-country-name

 

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:

Collapse | Copy Code
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:

Collapse | Copy Code
IP Number = 16777216*w + 65536*x + 256*y + z (1)

where:

Collapse | Copy Code
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.

Collapse | Copy Code
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:

Collapse | Copy Code
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:

Collapse | Copy Code
"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
Collapse | Copy Code
"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:

Collapse | Copy Code
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:

License

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

 
 
 
 
 
A free IP-Country List can be obtained at http://www.ip2nation.com/ The database is in SQL format. It can be imported/restored into MySQL, MSSQL, SQLite or any database that uses standard SQL query. Below is a sample of retrieving the Country from IP:

public static string GetCountry()
{
string ip = "66.249.73.168";
string country = ""; if (ip == "::1" || ip == "127.0.0.1")
return "Localhost"; 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; using (MySqlConnection conn = new MySqlConnection(config.ConStr))
{
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.Connection = conn;
conn.Open(); cmd.CommandText = @"select a.country from ip2nationcountries a
inner join ip2nation b on a.code = b.country
where b.ip < " + ipNumber + @"
order by b.ip desc limit 0,1;";
country = cmd.ExecuteScalar() + ""; conn.Close();
}
}
return country;
}

[转]How to convert IP address to country name的更多相关文章

  1. Java – Convert IP address to Decimal Number

    In this tutorial, we show you how to convert an IP address to its decimal equivalent in Java, and vi ...

  2. Convert IPv6 Address to IP numbers (C#)

    URL: http://lite.ip2location.com/ Use the code below to convert the IP address of your web visitors ...

  3. IP Address 分类: POJ 2015-06-12 19:34 12人阅读 评论(0) 收藏

    IP Address Time Limit: 1000MS   Memory Limit: 30000K Total Submissions: 19125   Accepted: 11053 Desc ...

  4. 华东师大OJ:IP Address【IP地址转换】

    /*===================================== IP Address Time Limit:1000MS Memory Limit:30000KB Total Subm ...

  5. poj2105 IP Address(简单题)

    题目链接:id=2105">http://poj.org/problem?id=2105 ----------------------------------------------- ...

  6. IP address/地址 检查

    1.Determine if a string is a valid IP address in C Beej's Guide to Network Programming 2.9.14. inet_ ...

  7. OpenJudge/Poj 2105 IP Address

    1.链接地址: http://poj.org/problem?id=2105 http://bailian.openjudge.cn/practice/2105 2.题目: IP Address Ti ...

  8. ZOJ2482 IP Address 2017-04-18 23:11 44人阅读 评论(0) 收藏

    IP Address Time Limit: 2 Seconds      Memory Limit: 65536 KB Suppose you are reading byte streams fr ...

  9. lwip IP address handling 关于 IP 地址的 操作 API接口

    lwip 2.0.3  IP address handling /** * @file * IP address API (common IPv4 and IPv6) */ 1.u32_t ipadd ...

随机推荐

  1. PID入门的十五个基本概念

    PID调节系统PID功能由PID调节器或DCS系统内部功能程序模块实现,了解与PID调节相关的一些基本概念,有助于PID入门新手快速熟悉调节器应用,在自动调节系统中成功整定PID参数.1.被调量被调量 ...

  2. PAC(Proxy Auto Config)代理自动配置文件的编写

    Proxy Auto Config文件格式说明 PAC文件实际上是一个Script, 通过PAC我们可以让系统根据情况判断使用哪一个Proxy来访问目标网址, 这样做的好处: 分散Proxy的流量,避 ...

  3. C#全角半角转换函数

    Code#region 全角半角转换 /// <summary> /// 转全角的函数(SBC case) /// </summary> /// <param name= ...

  4. hibernate中session,HQL,持久化,一对多,多对一

    package com.hanqi.test; import java.util.Date; import java.util.List; import org.hibernate.Query; im ...

  5. 比较器comparable与comparator的使用

    在Java学习和使用里,工具类与算法类(collections和Arrays)也是我们使用比较多的,在它们里面就包含了comparable与comparator这两种比较器. 一.比较器的分类与概念 ...

  6. JAVA事务的概念

    From:http://www.cnblogs.com/kristain/articles/2038397.html 一.什么是事务 事务是访问数据库的一个操作序列,数据库应用系统通过事务集来完成对数 ...

  7. mysql xtarbackup备份脚本

    #!/bin/sh # # # Script config User="user" Password="passwd" Basedir=/application ...

  8. oracle安装界面中文乱码解决

    在安装oracle时如果我们用的是英文安装没有任何问题,但是我要安装中文的,结果中文界面就出现了乱码了,后来网上找了原因是要安装中文包才可以,下面我来介绍一下. 在Linux的X window里安装o ...

  9. vector 与map的下标操作

    1.vector的下标操作不会添加元素,只能针对已经存在的元素操作. 2.map的下标操作具有副作用,key不存在,会在map中添加一个具有该key的新元素,新元素的value使用默认构造方法. 3. ...

  10. linux自己带的apache重新启动

    如果是linux自己带的apache的话就使用命令 service httpd start 启动 service httpd stop 关闭 service httpd restart 重新启动 如果 ...