[转]How to convert IP address to country name
本文转自: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:

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
- Download the latest IP-to-Country database (Last updated on July 21 2008).
- The IP-to-Country Handbook
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:
License
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
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的更多相关文章
- 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 ...
- 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 ...
- IP Address 分类: POJ 2015-06-12 19:34 12人阅读 评论(0) 收藏
IP Address Time Limit: 1000MS Memory Limit: 30000K Total Submissions: 19125 Accepted: 11053 Desc ...
- 华东师大OJ:IP Address【IP地址转换】
/*===================================== IP Address Time Limit:1000MS Memory Limit:30000KB Total Subm ...
- poj2105 IP Address(简单题)
题目链接:id=2105">http://poj.org/problem?id=2105 ----------------------------------------------- ...
- IP address/地址 检查
1.Determine if a string is a valid IP address in C Beej's Guide to Network Programming 2.9.14. inet_ ...
- OpenJudge/Poj 2105 IP Address
1.链接地址: http://poj.org/problem?id=2105 http://bailian.openjudge.cn/practice/2105 2.题目: IP Address Ti ...
- 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 ...
- 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 ...
随机推荐
- Java中可重入锁ReentrantLock原理剖析
本文由码农网 – 吴极心原创,转载请看清文末的转载要求,欢迎参与我们的付费投稿计划! 一. 概述 本文首先介绍Lock接口.ReentrantLock的类层次结构以及锁功能模板类AbstractQue ...
- CodeForces 489A SwapSort (选择排序法)
SwapSort 题目链接: http://acm.hust.edu.cn/vjudge/contest/121332#problem/A Description In this problem yo ...
- CABasicAnimation精讲
前言 本教程写了这个效果图的demo,同时总结CABasicAnimation的使用方法. 看完gif动画完,看到了什么?平移.旋转.缩放.闪烁.路径动画. 实现平移动画 实现平移动画,我们可以通过t ...
- hdu2121 - Ice_cream’s world II(朱刘算法,不固定根)
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2121 题目意思大概是要你在一些城市中选一个做首都 , 要求首都都能到其他城市 , 道路花费要最少 , ...
- Java学习笔记(一):数据类型与变量
数据类型 Java中存在2种数据类型,下面我们来详解一下: 基本数据类型: 引用数据类型: 可以用一张表来记录: 基本数据类型 整型 byte:1个字节8位,取值范围为:[-128, 127],直接写 ...
- JS 命名空间 实现方式 收集
一. 对象注册式 // 声明一个全局对象Namespace,用来注册命名空间Namespace = new Object(); // 全局对象仅仅存在register函数,参数为名称空间全路径,如&q ...
- JAVA 正则表达式 (超详细)
(PS:这篇文章为转载,我不喜欢转载的但我觉得这篇文章实在是超赞了,就转了过来,这篇可以说是学习JAVA正则表达的必读篇.作者是个正真有功力的人,阅读愉快) 在Sun的Java JDK 1.40版本中 ...
- Mybatis学习之配置文件
Mybatis也是ORM框架的一种,与Hibernate框架的不同就是Hibernate框架是实体与表的映射,是一种全自动的ORM实现,而Mybatis是实体与sql语句的映射,是一种半自动的ORM映 ...
- cocos2d-x 图形绘制
转自:http://blog.csdn.net/zhy_cheng/article/details/8480048 图形绘制的话,在cocos2d-x自带的TestCpp里有,包括绘制点,直线,多边形 ...
- WinDbug之DUMP蓝屏分析
Microsoft (R) Windows Debugger Version 6.2.8400.0 X86Copyright (c) Microsoft Corporation. All rights ...