Appearance
IP9免费IP查询API Python/Go/Java接入教程(2026最新版)
引言
开发者在做地理定位、风控、广告投放等功能时,经常需要稳定免费的IP归属地API。IP9.com.cn 以其无需注册、响应快、精度高的特点,成为很多人的首选。
本文提供Python、Go、Java三种常用语言的完整接入示例,并分享生产级最佳实践。
快速上手
接口地址:
http
GET https://ip9.com.cn/get?ip=58.30.0.0返回示例(JSON):
json
{
"ret": 200, // 200为正常
"data": {
"ip": "58.30.0.0", // 查询的IP地址
"country": "中国", // 国家/地区
"country_code": "cn", // 国家/地区简码
"prov": "北京", // 省份
"city": "北京", // 城市
"city_code": "beijing", // 城市简码
"city_short_code": "bj", // 城市简码
"area": "东城", // 区县
"post_code": "100000", //邮政编码
"area_code": "010", // 电话区号
"isp": "中国移动", // 运营商
"lng": "116.41005", // 城市中心-经度
"lat": "39.93157", // 城市中心-纬度
"long_ip": 975044608, // longip
"big_area": "华北", // 国内大区划分
},
"qt": 0.001 // 查询时间-秒
}Python 接入
python
import requests
from cachetools import TTLCache
cache = TTLCache(maxsize=500, ttl=300) # 5分钟缓存
def query_ip(ip=""):
if ip in cache:
return cache[ip]
try:
url = f"https://ip9.com.cn/get?ip={ip}" if ip else "https://ip9.com.cn/get"
r = requests.get(url, timeout=3)
data = r.json()
if data["ret"] == 200:
cache[ip] = data["data"]
return data["data"]
except:
pass
return NoneGo 语言接入
go
package main
import (
"encoding/json"
"fmt"
"net/http"
"time"
)
type IPInfo struct {
Ret int `json:"ret"`
Data struct {
IP string `json:"ip"`
Prov string `json:"prov"`
City string `json:"city"`
ISP string `json:"isp"`
IPType string `json:"ip_type"`
} `json:"data"`
}
func GetIPInfo(ip string) (*IPInfo, error) {
url := "https://ip9.com.cn/get"
if ip != "" {
url += "?ip=" + ip
}
client := &http.Client{Timeout: 3 * time.Second}
resp, err := client.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var info IPInfo
json.NewDecoder(resp.Body).Decode(&info)
return &info, nil
}Java 接入
(类似结构,提供HttpClient示例)
生产最佳实践
- 实现本地缓存
- 异常重试机制
- 监控响应时间和成功率
- 结合Redis做分布式缓存
总结
IP9 API接入简单,适合各种规模项目。推荐给需要的朋友。
更多示例见IP9官网:https://www.ip9.com.cn 首页。