是否有好用的ip地址库可以推荐
目前在做一个统计分析系统,最主要的是要分析ip来源得知用户是来自那个地方,目前找到了两个库,一个是纯真IP库,这个库太过业余,我需要的效果是从国家->省->市,这样一个层级的地理位置信息,显然它不能给我。另一个是国外的地址库,虽然它的格式挺标准的,但是基本不支持国内的城市,所以也不符合我的要求。
网上还有类似maxmind这样的webservice可以查询到地理接口,但是因为它限制了每天的ip查询次数,而且这些统计信息都是即时入库,远程调用接口也不靠谱。
因此是否有支持中文的,有比较标准的地理位置信息的ip地址库推荐,当然是要免费的。
5 个回答
http://ip.taobao.com/
这个我在OSChina上得知的,超给力:
- 提供国家、省、市、县、运营商全方位信息,信息维度广,格式规范
- 提供完善的统计分析报表,省准确度超过99.8%,市准确度超过96.8%,数据质量有保障。
http://developer.baidu.com/map/ip-loc...
百度的 LBS 服务。支持根据 IP 查找位置信息。以上地址是相关文档
示例:
http://api.map.baidu.com/location/ip?...
返回值:
{ address: "CN|吉林|长春|None|CERNET|1|None", content: { address_detail: { province: "吉林省", city: "长春市", district: "", street: "", street_number: "", city_code: 53 }, address: "吉林省长春市", point: { y: "5419815.34", x: "13950002.65" } }, status: 0 }
可以用淘宝的,符合你的要求
http://ip.taobao.com/
2013-08-14 19:43:43
原始出处 、作者信息和本声明。否则将追究法律责任。http://liyaoyi.blog.51cto.com/442933/1273031
一、通过淘宝API接口
接口说明:
1. 请求接口(GET):
http://ip.taobao.com/service/getIpInfo.php?ip=[ip地址字串]
2. 响应信息:
(json格式的)国家 、省(自治区或直辖市)、市(县)、运营商
3. 返回数据格式:
{"code":0,"data":{"ip":"210.75.225.254","country":"\u4e2d\u56fd","area":"\u534e\u5317",
"region":"\u5317\u4eac\u5e02","city":"\u5317\u4eac\u5e02","county":"","isp":"\u7535\u4fe1",
"country_id":"86","area_id":"100000","region_id":"110000","city_id":"110000",
"county_id":"-1","isp_id":"100017"}}
其中code的值的含义为,0:成功,1:失败。
1
2
3
4
5
6
7
8
9
10
11
12
13
|
#!/usr/bin/python #coding:utf-8 import
import
ip = raw_input ( "请输入要查询的IP:" ) apiurl = "http://ip.taobao.com/service/getIpInfo.php?ip=%s" % ip content = urllib2.urlopen(apiurl).read() data = json.loads(content)[ 'data' ] code = json.loads(content)[ 'code' ] if
= = 0 :
print "\nIP: %s Form: %s%s%s ISP: %s\n" (data[ 'ip' ], data[ 'country' ], data[ 'region' ], 'city' ], data[ 'isp' ]) else :
print data |
二、通过ip138
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
#!/usr/bin/python #coding:utf-8 import
import
p = re. compile (r '.*<li>(.*)</li><li>(.*)</li>.*' ) p_ip = re. compile (r '^(?:(?:[1-9]?[0-9]|1[0-9]{2}|2(?:[0-4][0-9]|5[0-5]))\.){3}(?:[1-9]?[0-9]|1[0-9]{2}|2(?:[0-4][0-9]|5[0-5]))$' ) ip = raw_input ( "请输入要查询的IP:" ) if
apiurl = "http://www.ip138.com/ips138.asp?ip=%s" % ip
content = urllib2.urlopen(apiurl).read()
ipline = p.search(content).group()
print p.sub(r '\1\n\2' ,ipline).decode( 'gbk' ) else :
print "Error:请输入正确的IP" |
其实只是用来练习写脚本而已,平时如果要查询一个IP,直接打开百度搜索就出来了。
原帖为python2.6写的http://liang3391.blog.51cto.com/178205/544754
看到一网友用python2.6写的一个脚本,处于好奇将其改写为python3,并做了小小的改动,在python3.2.3+win7及python3.2.2+SLES11 SP1下测试通过
- #!/usr/bin/env python
- import sys
- import http
- import http.client
- import urllib
- import re
- #http://www.ip138.com/ips1388.asp?ip=112.254.67.142&action=2
- if len(sys.argv) < 3:
- print("NO ip file found\nusage: python checkip.py ip.txt result.txt")
- sys.exit()
- web_url="www.ip138.com"
- u1="/ips1388.asp?ip="
- u2="218.31.158.174"
- u3="&action=2"
- fd=open(sys.argv[1],"r")
- #print("sys.argv[1]:",sys.argv[1])
- result=open(sys.argv[2],"w")
- for line in fd.readlines():
- #print("line:",line)
- geturl=u1+line.strip()+u3
- #print("url:",geturl)
- conn=http.client.HTTPConnection(web_url)
- conn.request("GET",geturl)
- r1=conn.getresponse()
- #print("status:",r1.status)
- data1=r1.read()
- #forma=sys.getfilesystemencoding()
- html=data1.decode("gbk")
- keyword=re.compile(r'''<td align="center"><ul class="ul1"><li>(.*?)</li><li>''', re.U|re.S)
- a=re.findall(keyword,html)
- #print("length:",len(a))
- #print(a)
- #print(type(a))
- s=line.strip() + "\t\t\t" + a[0]+"\n"
- if len(a)>0:
- print(s)
- result.write(s)
- else:
- print("Maybe have not web content")
- conn.close()
- fd.close()
- result.flush()
- result.close()
执行:
- python checkip.py ip.txt result.txt
result文件如下:
119.128.200.90 本站主数据:广东省东莞市 电信
218.90.169.90 本站主数据:江苏省无锡市 电信
219.129.242.180 本站主数据:广东省韶关市 电信
183.69.189.172 本站主数据:重庆市 电信
222.89.193.18 本站主数据:河南省平顶山市 电信
221.193.222.105 本站主数据:河北省邯郸市 联通
59.151.213.135 本站主数据:韩国
218.22.182.50 本站主数据:安徽省铜陵市 电信
124.238.192.23 本站主数据:湖北省武汉市 长城宽带
113.111.94.116 本站主数据:广东省广州市 电信
115.182.53.30 本站主数据:北京市 电信通
随着移动终端的普及,很多应用都基于LBS功能,附近的某某(餐馆、银行、妹纸等等)。
基础数据中,一般保存了目标位置的经纬度;利用用户提供的经纬度,进行对比,从而获得是否在附近。
目标:
查找附近的XXX,由近到远返回结果,且结果中有与目标点的距离。
针对查找附近的XXX,提出两个方案,如下:
一、方案A:
=================================================================================================
抽象为球面两点距离的计算,即已知道球面上两点的经纬度;
点(纬度,经度),A($radLat1,$radLng1)、B($radLat2,$radLng2);
优点:通俗易懂,部署简单便捷
缺点:每次都会查询数据库,性能堪忧
1、推导
通过余弦定理以及弧度计算方法,最终推导出来的算式A为:
$s = acos(cos($radLat1)*cos($radLat2)*cos($radLng1-$radLng2)+sin($radLat1)*sin($radLat2))*$R; |
目前网上大多使用Google公开的距离计算公司,推导算式B为:
$s = 2*asin(sqrt(pow(sin(($radLat1-$radLat2) /2 ),2)+cos($radLat1)*cos($radLat2)*pow(sin(($radLng1-$radLng2) /2 ),2)))*$R; |
其中 :
$radLat1、$radLng1,$radLat2,$radLng2 为弧度
$R 为地球半径
2、通过测试两种算法,结果相同且都正确,但通过PHP代码测试,两点间距离,10W次性能对比,自行推导版本计算时长算式B较优,如下:
//算式A
0.56368780136108float(431)
0.57460689544678float(431)
0.59051203727722float(431)
//算式B
0.47404885292053float(431)
0.47808718681335float(431)
0.47946381568909float(431)
3、所以采用数学方法推导出的公式:
<?php
// 根据经纬度计算距离其中A($lat1,$lng1)、B($lat2,$lng2)
public static function getDistance($lat1,$lng1,$lat2,$lng2)
{
// 地球半径
$R = 6378137;
// 将角度转为狐度
$radLat1 = deg2rad($lat1);
$radLat2 = deg2rad($lat2);
$radLng1 = deg2rad($lng1);
$radLng2 = deg2rad($lng2);
// 结果
$s = acos(cos($radLat1)*cos($radLat2)*cos($radLng1-$radLng2)+sin($radLat1)*sin($radLat2))*$R;
// 精度
$s = round($s* 10000) /10000 ;
return round($s);
}
?> |
4、在实际应用中,需要从数据库中遍历取出符合条件,以及排序等操作,
将所有数据取出,然后通过PHP循环对比,筛选符合条件结果,显然性能低下;所以我们利用下Mysql存储函数来解决这个问题吧。
4.1、创建Mysql存储函数,并对经纬度字段建立索引
<?php
// 根据经纬度计算距离其中A($lat1,$lng1)、B($lat2,$lng2)
public static function getDistance($lat1,$lng1,$lat2,$lng2)
{
// 地球半径
$R = 6378137;
// 将角度转为狐度
$radLat1 = deg2rad($lat1);
$radLat2 = deg2rad($lat2);
$radLng1 = deg2rad($lng1);
$radLng2 = deg2rad($lng2);
// 结果
$s = acos(cos($radLat1)*cos($radLat2)*cos($radLng1-$radLng2)+sin($radLat1)*sin($radLat2))*$R;
// 精度
$s = round($s* 10000) /10000 ;
return round($s);
}
?> |
4.2、查询SQL
通过SQL,可设置距离以及排序;可搜索出符合条件的信息,以及有一个较好的排序
1 | SELECT *,latitude,longitude,GETDISTANCE(latitude,longitude,30.663262,104.071619) AS distance FROM |
二、方案B
=================================================================================================
Geohash算法;geohash是一种地址编码,它能把二维的经纬度编码成一维的字符串。
比如,成都永丰立交的编码是wm3yr31d2524
优点:
1、利用一个字段,即可存储经纬度;搜索时,只需一条索引,效率较高
2、编码的前缀可以表示更大的区域,查找附近的,非常方便。 SQL中,LIKE ‘wm3yr3%’,即可查询附近的所有地点。
3、通过编码精度可模糊坐标、隐私保护等。
缺点: 距离和排序需二次运算(筛选结果中运行,其实挺快)
1、geohash的编码算法
成都永丰立交经纬度(30.63578,104.031601)
1.1、纬度范围(-90, 90)平分成两个区间(-90, 0)、(0, 90),如果目标纬度位于前一个区间,则编码为0,否则编码为1。
由于30.625265属于(0, 90),所以取编码为1。
然后再将(0, 90)分成 (0, 45), (45, 90)两个区间,而39.92324位于(0, 45),所以编码为0,
然后再将(0, 45)分成 (0, 22.5), (22.5, 45)两个区间,而39.92324位于(22.5, 45),所以编码为1,
依次类推可得永丰立交纬度编码为101010111001001000100101
1.2、经度也用同样的算法,对(-180, 180)依次细分,(-180,0)、(0,180) 得出编码110010011111101001100000
1.3、合并经纬度编码,从高到低,先取一位经度,再取一位纬度;得出结果 111001001100011111101011
1.4、用0-9、b-z(去掉a, i, l, o)这32个字母进行base32编码,得到(30.63578,104.031601)的编码为wm3yr31d2524。
|
11100 10011 00011 11110 10111 00011 00001 01100 00010 00101 00010 00100 => wm3yr31d2524
十进制 base32 十进制 base32 v w |
2、策略
1、在纬度和经度入库时,数据库新加一字段geohash,记录此点的geohash值
2、查找附近,利用 在SQL中 LIKE ‘wm3yr3%’;且此结果可缓存;在小区域内,不会因为改变经纬度,而重新数据库查询
3、查找出的有限结果,如需要求距离或者排序,可利用距离公式和二维数据排序;此时也是少量数据,会很快的。
3、PHP基类
geohash.class.php
<?php
class Geohash {
private $coding= "0123456789bcdefghjkmnpqr ;
private $codingMap=array();
public function Geohash()
{
for ($i=0; $i<32; $i++)
{
$this->codingMap[substr($this->coding,$i,1)]=str_pad(decbin($i), 5, "0" , STR_PAD_LEFT);
}
}
public function decode($ hash )
{
$binary= "" ;
$hl=strlen($ hash );
for ($i=0; $i<$hl; $i++)
{
$binary.=$this->codingMap[substr($ hash ,$i,1)];
}
$bl=strlen($binary);
$blat= "" ;
$blong= "" ;
for ($i=0; $i<$bl; $i++)
{
if ($i%2)
$blat=$blat.substr($binary,$i,1);
else
$blong=$blong.substr($binary,$i,1);
}
$lat=$this->binDecode($blat,-90,90);
$long=$this->binDecode($blong,-180,180);
$latErr=$this->calcError(strlen($blat),-90,90);
$longErr=$this->calcError(strlen($blong),-180,180);
$latPlaces=max(1, -round(log10($latErr))) - 1;
$longPlaces=max(1, -round(log10($longErr))) - 1;
$lat=round($lat, $latPlaces);
$long=round($long, $longPlaces);
return array($lat,$long);
}
public function encode($lat,$long)
{
$plat=$this->precision($lat);
$latbits=1;
$err=45;
while ($err>$plat)
{
$latbits++;
$err/=2;
}
$plong=$this->precision($long);
$longbits=1;
$err=90;
while ($err>$plong)
{
$longbits++;
$err/=2;
}
$bits=max($latbits,$longbits);
$longbits=$bits;
$latbits=$bits;
$addlong=1;
while (($longbits+$latbits)%5 != 0)
{
$longbits+=$addlong;
$latbits+=!$addlong;
$addlong=!$addlong;
}
$blat=$this->binEncode($lat,-90,90, $latbits);
$blong=$this->binEncode($long,-180,180,$longbits);
$binary= "" ;
$uselong=1;
while (strlen($blat)+strlen($blong))
{
if ($uselong)
{
$binary=$binary.substr($blong,0,1);
$blong=substr($blong,1);
}
else
{
$binary=$binary.substr($blat,0,1);
$blat=substr($blat,1);
}
$uselong=!$uselong;
}
$ hash = "" ;
for ($i=0; $i<strlen($binary); $i+=5)
{
$n=bindec(substr($binary,$i,5));
$ hash =$ hash .$this->coding[$n];
}
return $ hash ;
}
private function calcError($bits,$min,$max)
{
$err=($max-$min) /2 ;
while ($bits--)
$err/=2;
return $err;
}
private function precision($number)
{
$precision=0;
$pt=strpos($number, '.' );
if ($pt!== false )
{
$precision=-(strlen($number)-$pt-1);
}
return pow(10,$precision) /2 ;
}
private function binEncode($number, $min, $max, $bitcount)
{
if ($bitcount==0)
return "" ;
$mid=($min+$max) /2 ;
if ($number>$mid)
return "1" .$this->binEncode($number, $mid, $max,$bitcount-1);
else
return "0" .$this->binEncode($number, $min, $mid,$bitcount-1);
}
private function binDecode($binary, $min, $max)
{
$mid=($min+$max) /2 ;
if (strlen($binary)==0)
return $mid;
$bit=substr($binary,0,1);
$binary=substr($binary,1);
if ($bit==1)
return $this->binDecode($binary, $mid, $max);
else
return $this->binDecode($binary, $min, $mid);
} }
?> |
三、测试
<?php
require_once( 'Mysql.class.php' ); require_once( 'geohash.class.php' );
//mysql $conf = array(
'host' => '127.0.0.1' ,
'port' => 3306,
'user' => 'root' ,
'password' => '123456' ,
'database' => 'mocube' ,
'charset' => 'utf8' ,
'persistent' => false );
$mysql = new Db_Mysql($conf); $geohash=new Geohash;
// 经纬度转换成Geohash
// 获取附近的信息 $n_latitude = $_GET[ 'la' ]; $n_longitude = $_GET[ 'lo' ];
// 开始 $b_time = microtime( true );
// 方案A,直接利用数据库存储函数,遍历排序
// 方案B geohash求出附近,然后排序
// 当前 geohash值 $n_geohash = $geohash->encode($n_latitude,$n_longitude);
// 附近 $n = $_GET[ 'n' ]; $like_geohash = substr($n_geohash, 0, $n);
$sql = 'select * from mb_shop_ext where geohash like "' .$like_geohash. '%"' ;
echo $sql;
$data = $mysql->queryAll($sql);
// 算出实际距离 foreach($data as $key=>$val) {
$distance = getDistance($n_latitude,$n_longitude,$val[ 'latitude' ],$val[ 'longitude' ]);
$data[$key][ 'distance' ] = $distance;
// 排序列
$sortdistance[$key] = $distance; }
// 距离排序 array_multisort($sortdistance,SORT_ASC,$data);
// 结束 $e_time = microtime( true );
echo $e_time - $b_time;
var_dump($data);
// 根据经纬度计算距离其中A($lat1,$lng1)、B($lat2,$lng2) function getDistance($lat1,$lng1,$lat2,$lng2) {
// 地球半径
$R = 6378137;
// 将角度转为狐度
$radLat1 = deg2rad($lat1);
$radLat2 = deg2rad($lat2);
$radLng1 = deg2rad($lng1);
$radLng2 = deg2rad($lng2);
// 结果
$s = acos(cos($radLat1)*cos($radLat2)*cos($radLng1-$radLng2)+sin($radLat1)*sin($radLat2))*$R;
// 精度
$s = round($s* 10000) /10000 ;
return round($s); }
?> |
四、总结
方案B的亮点在于:
1、搜索结果可缓存,重复使用,不会因为用户有小范围的移动,直接穿透数据库查询。
2、先缩小结果范围,再运算、排序,可提升性能。
254条记录,性能对比,
在实际应用场景中,方案B数据库搜索可内存缓存;且如数据量更大,方案B结果会更优。
方案A:
0.016560077667236
0.032402992248535
0.040318012237549
方案B
0.0079810619354248
0.0079669952392578
0.0064868927001953
五、其他
两种方案,根据应用场景以及负载情况合理选择,当然推荐方案B;
不管哪种方案,都记得,给列加上索引,利于数据库检索。