1、淘宝API接口:
文档:http://ip.taobao.com/instructions
示例:
GET http://ip.taobao.com/outGetIpInfo?ip=221.218.209.125&accessKey=alibaba-inc
{
data: {
area: "",
country: "中国",
isp_id: "100026",
queryIp: "221.218.209.125",
city: "北京",
ip: "221.218.209.125",
isp: "联通",
county: "",
region_id: "110000",
area_id: "",
county_id: null,
region: "北京",
country_id: "CN",
city_id: "110100"
},
msg: "query success",
code: 0
}
2、IP-API接口:
文档:https://ip-api.com/docs/api:json
示例:
GET http://ip-api.com/json/221.218.209.125?lang=zh-CN
{
status: "success",
country: "中国",
countryCode: "CN",
region: "BJ",
regionName: "北京市",
city: "北京",
zip: "",
lat: 39.9285,
lon: 116.385,
timezone: "Asia/Shanghai",
isp: "China Unicom Beijing Province Network",
org: "",
as: "AS4808 China Unicom Beijing Province Network",
query: "221.218.209.125"
}
3、太平洋IP接口:
文档:http://whois.pconline.com.cn/
示例:
GET http://whois.pconline.com.cn/ipJson.jsp?ip=221.218.209.125&json=true
{
ip: "221.218.209.125",
pro: "北京市",
proCode: "110000",
city: "北京市",
cityCode: "110000",
region: "海淀区",
regionCode: "110108",
addr: "北京市海淀区 联通ADSL",
regionNames: "",
err: ""
}
网络请求库,使用 Requests(PHP:rmccue/requests进行网络请求)
通过ip获取位置信息不太准确,需要对获取的省市县三级区域码做判断处理
<?php
namespace app\service;
use app\common\AppException;
use Requests;
class IpService
{
public static function getIpInfo($ip)
{
$base_url = 'http://whois.pconline.com.cn/ipJson.jsp';
$params = [
'ip' => $ip,
// 注意,此处不能写boolean值,需要给string
'json' => 'true'
];
$url = $base_url . '?' . http_build_query($params);
$response = Requests::get($url);
if ($response->success) {
// 编码转换处理,并移除字符串两边的空白
$body=iconv("GBK", "UTF-8", trim($response->body));
$data = json_decode($body, true);
// 优先取区县码
$code = $data['regionCode'];
// 其次取城市码
if (!self::isRegionCode($code)) {
$code = $data['cityCode'];
}
//再次取省份码
if (!self::isRegionCode($code)) {
$code = $data['proCode'];
}
return [
'ip' => $data['ip'],
'code' => $code
];
// 此处仅返回区位码即可
return [
'ip' => $data['ip'],
'code' => $data['regionCode'],
];
} else {
throw new AppException('ip信息获取失败');
}
}
public static function isRegionCode($code)
{
if (empty($code) || count($code) != 6) {
return false;
} else {
return true;
}
}
}
异常类
<?php
namespace app\common;
use Exception;
/**
* 自定义的业务异常
* Class AppException
* @package app\common
*/
class AppException extends Exception
{
}
# -*- coding: utf-8 -*-
"""
@File : ip_util.py
@Date : 2022-10-13
"""
import requests
def get_ip_info(ip):
url = 'http://ip.taobao.com/outGetIpInfo'
params = {
'ip': ip,
'accessKey': 'alibaba-inc'
}
res = requests.get(url, params)
if not res.ok:
res.raise_for_status()
return res.json().get('data')
if __name__ == '__main__':
print(get_ip_info('221.218.209.125'))
输出结果
{
'area': '',
'country': '中国',
'isp_id': '100026',
'queryIp': '221.218.209.125',
'city': '北京',
'ip': '221.218.209.125',
'isp': '联通',
'county': '',
'region_id': '110000',
'area_id': '',
'county_id': None,
'region': '北京',
'country_id': 'CN',
'city_id': '110100'
}