前端獲取用戶 IP 及地理位置常用第三方 API 整理,涵蓋騰訊、新浪、搜狐、谷歌、有道等主流服務商,對比返回格式、調用方式、適用場景。
| 服務商 | 接口地址 | 返回格式 | 支持協議 | 備註 |
|---|---|---|---|---|
| 騰訊 | https://fw.qq.com/ipaddress | JS 變量 | HTTP | 需腳本引入,返回 IPData 數組 |
| 新浪 | https://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js | JS 變量 | HTTP | 返回 remote_ip_info 對象,含 Unicode 編碼 |
| 搜狐 | https://pv.sohu.com/cityjson | JS 變量 | HTTP | 返回 returnCitySN 對象,極簡 |
| 谷歌 | https://j.maxmind.com/app/geoip.js | JS 變量 | HTTP | MaxMind 服務,需引用腳本 |
| 有道 | https://www.youdao.com/smartresult-xml/search.s | XML/JS | HTTP | 參數較複雜 |
| 1616 | https://w.1616.net/chaxun/iptolocal.php | HTML/JS | HTTP | 老牌查詢站 |
| 126 | https://ip.ws.126.net/ipquery | JS 變量 | HTTP | 網易服務 |
| hao123 | https://app.hao123.com/ipquery/getcity.php?rtype=2 | JSONP | HTTP | 支持 callback 參數 |
<script src="https://fw.qq.com/ipaddress"></script>
<script>
document.write("IP: " + IPData[0] + ", 地址: " + IPData[2] + " " + IPData[3]);
// IPData = ["58.218.198.205", "", "江蘇省", "徐州市"]
</script>
var remote_ip_info = {
"ret": 1,
"start": "123.68.0.0",
"end": "123.68.195.255",
"country": "中國",
"province": "湖南",
"city": "長沙",
"district": "",
"isp": "鐵通",
"type": "",
"desc": ""
};
var returnCitySN = {
"cip": "123.68.122.147",
"cid": "430000",
"cname": "湖南省"
};
function getUserIP() {
const apis = [
{url: 'https://api.ipify.org?format=json', parser: d => d.ip},
{url: 'https://httpbin.org/ip', parser: d => d.origin},
{url: 'https://ipapi.co/json/', parser: d => d.ip},
];
return Promise.any(apis.map(api =>
fetch(api.url).then(r => r.json()).then(api.parser)
));
}
// 使用
getUserIP().then(ip => console.log('用戶 IP:', ip));
async function getGeoInfo() {
try {
const res = await fetch('https://ipapi.co/json/');
const data = await res.json();
return {
ip: data.ip,
city: data.city,
region: data.region,
country: data.country_name,
isp: data.org,
lat: data.latitude,
lon: data.longitude,
};
} catch (e) {
return null;
}
}
function jsonp(url, callbackName = 'callback') {
return new Promise((resolve, reject) => {
const cb = `jsonp_${Date.now()}_${Math.random().toString(36).substr(2)}`;
window[cb] = (data) => {
resolve(data);
delete window[cb];
document.head.removeChild(script);
};
const script = document.createElement('script');
script.src = `${url}${url.includes('?') ? '&' : '?'}${callbackName}=${cb}`;
script.onerror = () => reject(new Error('JSONP load failed'));
document.head.appendChild(script);
});
}
// 搜狐調用
jsonp('https://pv.sohu.com/cityjson').then(data => {
console.log(data.returnCitySN);
});
<?php
function getClientIP() {
$headers = [
'HTTP_CF_CONNECTING_IP', // Cloudflare
'HTTP_X_FORWARDED_FOR', // 標準代理
'HTTP_X_REAL_IP', // Nginx proxy
'HTTP_CLIENT_IP',
'REMOTE_ADDR',
];
foreach ($headers as $header) {
if (!empty($_SERVER[$header])) {
$ips = explode(',', $_SERVER[$header]);
$ip = trim($ips[0]);
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
return $ip;
}
}
}
return $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
}
// 結合離線數據庫 (MaxMind GeoIP2)
require 'vendor/autoload.php';
$reader = new GeoIp2\Database\Reader('GeoLite2-City.mmdb');
$record = $reader->city(getClientIP());
echo $record->country->name . ' ' . $record->city->name;
ipapi.co、ipinfo.io、cloudflare.com/cdn-cgi/trace (HTTPS、JSON、CORS 友好)pv.sohu.com/cityjson (極簡、無依賴)第三方免費 API 穩定性無保障,核心業務建議自建或采購商業服務。