读取全球ip获取用户地区
这个 首先说明下。ip库是qq纯真ip库 dat文件类型
public static string QQipPath = AppDomain.CurrentDomain.BaseDirectory + "\\ipdata\\qqwry.dat";///QQ纯真ip库地址
public static string GetCity(string IP)
{
string ipfilePath = QQipPath;
IPSearch ipSearch = new IPSearch(ipfilePath);
IPSearch.IPLocation loc = ipSearch.GetIPLocation(IP);
return loc.country;
}
public class IPSearch
{
FileStream ipFile;
long ip;
string ipfilePath;
///<summary>
/// 构造函数
///</summary>
///<param name="ipfilePath">纯真IP数据库路径</param>
public IPSearch(string ipfilePath)
{
this.ipfilePath = ipfilePath;
}
///<summary>
/// 地理位置,包括国家和地区
///</summary>
public struct IPLocation
{
public string country, area;
}
///<summary>
/// 获取指定IP所在地理位置
///</summary>
///<param name="strIP">要查询的IP地址</param>
///<returns></returns>
public IPLocation GetIPLocation(string strIP)
{
ip = IPToLong(strIP);
ipFile = new FileStream(ipfilePath, FileMode.Open, FileAccess.Read);
long[] ipArray = BlockToArray(ReadIPBlock());
long offset = SearchIP(ipArray, 0, ipArray.Length - 1) * 7 + 4;
ipFile.Position += offset;//跳过起始IP
ipFile.Position = ReadLongX(3) + 4;//跳过结束IP
IPLocation loc = new IPLocation();
int flag = ipFile.ReadByte();//读取标志
if (flag == 1)//表示国家和地区被转向
{
ipFile.Position = ReadLongX(3);
flag = ipFile.ReadByte();//再读标志
}
long countryOffset = ipFile.Position;
loc.country = ReadString(flag);
if (flag == 2)
{
ipFile.Position = countryOffset + 3;
}
flag = ipFile.ReadByte();
loc.area = ReadString(flag);
ipFile.Close();
ipFile = null;
return loc;
}
///<summary>
/// 将字符串形式的IP转换位long
///</summary>
///<param name="strIP"></param>
///<returns></returns>
public long IPToLong(string strIP)
{
byte[] ip_bytes = new byte[8];
string[] strArr = strIP.Split(new char[] { '.' });
if (strArr.Length - 1 >= 3)
{
for (int i = 0; i < 4; i++)
{
ip_bytes[i] = byte.Parse(strArr[3 - i]);
}
}
return BitConverter.ToInt64(ip_bytes, 0);
}
///<summary>
/// 将索引区字节块中的起始IP转换成Long数组
///</summary>
///<param name="ipBlock"></param>
long[] BlockToArray(byte[] ipBlock)
{
long[] ipArray = new long[ipBlock.Length / 7];
int ipIndex = 0;
byte[] temp = new byte[8];
for (int i = 0; i < ipBlock.Length; i += 7)
{
Array.Copy(ipBlock, i, temp, 0, 4);
ipArray[ipIndex] = BitConverter.ToInt64(temp, 0);
ipIndex++;
}
return ipArray;
}
///<summary>
/// 从IP数组中搜索指定IP并返回其索引
///</summary>
///<param name="ipArray">IP数组</param>
///<param name="start">指定搜索的起始位置</param>
///<param name="end">指定搜索的结束位置</param>
///<returns></returns>
int SearchIP(long[] ipArray, int start, int end)
{
int middle = (start + end) / 2;
if (middle == start)
return middle;
else if (ip < ipArray[middle])
return SearchIP(ipArray, start, middle);
else
return SearchIP(ipArray, middle, end);
}
///<summary>
/// 读取IP文件中索引区块
///</summary>
///<returns></returns>
byte[] ReadIPBlock()
{
long startPosition = ReadLongX(4);
long endPosition = ReadLongX(4);
long count = (endPosition - startPosition) / 7 + 1;//总记录数
ipFile.Position = startPosition;
byte[] ipBlock = new byte[count * 7];
ipFile.Read(ipBlock, 0, ipBlock.Length);
ipFile.Position = startPosition;
return ipBlock;
}
///<summary>
/// 从IP文件中读取指定字节并转换位long
///</summary>
///<param name="bytesCount">需要转换的字节数,主意不要超过8字节</param>
///<returns></returns>
long ReadLongX(int bytesCount)
{
byte[] _bytes = new byte[8];
ipFile.Read(_bytes, 0, bytesCount);
return BitConverter.ToInt64(_bytes, 0);
}
///<summary>
/// 从IP文件中读取字符串
///</summary>
///<param name="flag">转向标志</param>
///<returns></returns>
string ReadString(int flag)
{
if (flag == 1 || flag == 2)//转向标志
ipFile.Position = ReadLongX(3);
else
ipFile.Position -= 1;
List<byte> list = new List<byte>();
byte b = (byte)ipFile.ReadByte();
while (b > 0)
{
list.Add(b);
b = (byte)ipFile.ReadByte();
}
return Encoding.Default.GetString(list.ToArray());
}
public string GetUserIp()
{
string ip;
bool isErr = false;
if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_ForWARDED_For"] == null)
ip = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
else
ip = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_ForWARDED_For"].ToString();
if (ip.Length > 15)
{
if (ip.Contains(","))
{
ip = ip.Split(',')[0];
isErr = IsError(ip);
}
else
{
isErr = true;
}
}
else
{
isErr = IsError(ip);
}
if (isErr)
return "1.1.1.1";
else
return ip;
}
/// <summary>
/// ip过滤
/// </summary>
/// <param name="ip"></param>
/// <returns></returns>
protected bool IsError(string ip)
{
string[] temp;
bool isErr = false;
temp = ip.Split('.');
if (temp.Length == 4)
{
for (int i = 0; i < temp.Length; i++)
{
if (temp[i].Length > 3) isErr = true;
}
}
else
isErr = true;
return isErr;
}
public string GetIpAddress()
{
string result = String.Empty;
result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (result != null && result != String.Empty)
{
//可能有代理
if (result.IndexOf(".") == -1) //没有"."肯定是非IPv4格式
result = "1.1.1.1";
else
{
if (result.IndexOf(",") != -1)
{
//有",",估计多个代理。取第一个不是内网的IP。
result = result.Replace(" ", "").Replace("\"","");
string[] temparyip = result.Split(",;".ToCharArray());
for (int i = 0; i < temparyip.Length; i++)
{
if (!IsError(temparyip[i])
&& temparyip[i].Substring(0, 3) != "10."
&& temparyip[i].Substring(0, 7) != "192.168"
&& temparyip[i].Substring(0, 7) != "172.16.")
{
return temparyip[i]; //找到不是内网的地址
}
}
}
else if (!IsError(result)) //代理即是IP格式
return result;
else
result = "1.1.1.1"; //代理中的内容 非IP,取IP
}
}
string IpAddress = (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null && HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != String.Empty) ? HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] : HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
if (null == result || result == String.Empty)
result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
if (result == null || result == String.Empty)
result = HttpContext.Current.Request.UserHostAddress;
return result;
}
}
读取全球ip获取用户地区的更多相关文章
- 百度接口通过ip获取用户所在地
/** * 百度接口 * 通过用户ip获取用户所在地 * @param userIp * @return */ public static String get ...
- 根据ip获取用户地理位置
各大网站都提供根据ip获取用户地理位置信息,这里以新浪的接口为例子 接口地址为:http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js ...
- 百度地图api根据用户IP获取用户位置(PHP)
1.百度地图开放平台找的你的ak ,链接:http://lbsyun.baidu.com/apiconsole/key 2.获取用户ip地址(外网ip 服务器上可以获取用户外网Ip 本机ip地址只能获 ...
- php获取用户 地区 、ip地址
header("Content-type: text/html; charset=utf-8"); function getCity($ip = '')//获取地区 { if($i ...
- C# .net 如何根据访问者IP获取所在地区
第一步:在根目录添加新项(类),新建一个类文件,把以下文件粘贴到该类文件下: using System; using System.Collections.Generic; using Syste ...
- JSP通过IP获取用户(客户端)的地理位置信息
<%!//获取客户端的IP public String getRemoteIP(HttpServletRequest request) { if (request.getHeader(" ...
- PHP 根据IP获取地理位置
/** * 根据用户IP获取用户地理位置 * $ip 用户ip */ function get_position($ip){ if(empty($ip)){ return '缺少用户ip'; } $u ...
- js获取用户当前地理位置(省、市、经纬度)
在很多情况下,我们需要用到定位功能,来获取用户当前位置.当前比较流行的定位API有腾讯地图.百度地图.高德地图.搜狗地图等等,在这里我使用的是腾讯地图定位API,根据用户IP获取用户当前位置,API返 ...
- php 获取用户的IP、地址、来源
js方法获取用户的 ip 和 地址 <script src="http://pv.sohu.com/cityjson?ie=utf-8"></script> ...
随机推荐
- win10使用技巧
无法使用内置的管理员账户打开应用的问题命令行里输入:secpol.msc安全设置-本地策略-安全选项点击找到“用户账户控制:用于内置管理员账户的管理员批准”选项.该选项设置为"已启用&quo ...
- jquery ajax get /post
$.get(URL,callback); $("button").click(function(){ $.get("demo_test.asp",functio ...
- Delphi 完整的Bug决议工具EurekaLog的使用
http://blog.csdn.net/akof1314/article/details/6968587 Delphi 完整的Bug决议工具EurekaLog的使用 标签: delphi工具ftp ...
- php多条件搜索
PHP多条件查询 December : Tuesdayby 小屋 在我们的网站设计过程中,经常会用到多条件查询,本文的源码是一个二手房屋查询的例子.在本例中,我们要实现能够通过地理位置,物业类型,房屋 ...
- jQuery(window) 和 jQuery(document)的区别
jQuery(window).height()代表了当前可见区域的大小,而jQuery(document).height()则代表了整个文档的高度,可视具体情况使用
- HashMap的两种实现方式
本文主要简要分析了Java中和Redis中HashMap的实现,并且对比了两者的异同 1.Java的实现 下图表示了Java中一个HashMap的主要实现方式 因为大家对于Java中HashMap的实 ...
- Sass开发环境搭建
一.Ruby环境下Sass的安装 a.安装Ruby 1.下载rubyinstaller安装 2.命令行或者直接使用sass gem包安装Sass. ...
- 遗传算法之GAUL
遗传算法之GAUL简介 简介 GAUL(遗传算法工具库的简称) GAUL is an open source programming library, released under th ...
- TSkinData 皮肤控件后最大最小提示英文Close的解决方法
1.D:\soft\控件\VclSkin5.40-D7-D2010 New\source 控件安装位置 2.WinSkinForm.pas 查找Close 3.function TWinSkinFor ...
- Oracle:ORA-00955: name is already used by an existing object
下午从生产库导出了一份表结构,用来测试一些问题,由于生产库连接着其他用户下的表所以通过视图在本地模拟一下,于是创建视图: create or replace view csews as select ...