如何根据ip获取用户所在位置?
我们将描述如何从IP地址检索地理信息的过程。
为此,我们将使用MAxMind Perl API模块。该还提供一个数据文件GeoLiteCity,它是免费的,但不如付费版本准确。
首先我们需要下载GeoIP perl模块和数据文件:
$ cd $ mkdir GeoIP $ cd GeoIP $ wget http://geolite.maxmind.com/download/geoip/api/perl/Geo-IP-1.38.tar.gz $ wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz
在GeoIP目录中,提取这两个包:
$ tar xzf Geo-IP-1.38.tar.gz $ gunzip GeoLiteCity.dat.gz
在GeoIP目录中创建一个perl文件 iptolocation.pl
#!/usr/bin/perl use lib "Geo-IP-1.38/lib/"; use Geo::IP; my $gi = Geo::IP->open( "GeoLiteCity.dat", GEOIP_STANDARD ); my $r = $gi->record_by_name($ARGV[0]); if ($r) { print join( "\n", $r->country_code, $r->country_name, $r->city, $r->region, $r->region_name, $r->postal_code, $r->latitude, $r->longitude, $r->metro_code, $r->area_code ) . "\n"; } else { print "Location of this IP Address is NOT defined !\n"; }
添加可执行权限
$ chmod +x IPtoLocation.pl
执行脚本:
./IPtoLocation.pl 8.8.8.8
输出示例:
$ ./IPtoLocation.pl 8.8.8.8 US United States Mountain View CA California 94043 37.4192 -122.0574 807 650
日期:2020-07-07 20:54:49 来源:oir作者:oir