萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

主流 IP 地址查詢 API 整理(騰訊、新浪、搜狐、Google、有道等)含 JSONP 前端直連範例

前端無後端代理情況下,可直接呼叫各大廠商提供的 JSONP 介面取得訪客 IP 與地理位置。本文整理 8 家常用 API 的請求網址、回傳格式、前端調用範例,並附上跨域與可用性測試建議。

API 快速對照表

提供商介面網址回傳格式備註
騰訊https://fw.qq.com/ipaddressJS 變數 IPData 陣列[IP, '', 省份, 城市]
新浪https://int.dpool.sina.com.cn/iplookup/iplookup.php?format=jsJS 物件 remote_ip_info含國家、省、市、ISP、經緯度
搜狐https://pv.sohu.com/cityjsonJS 物件 returnCitySN含 cip、cid、cname
Googlehttps://j.maxmind.com/app/geoip.jsJS 變數需翻牆,國內不可用
有道https://www.youdao.com/smartresult-xml/search.sXML/JS參數較複雜
1616https://w.1616.net/chaxun/iptolocal.phpJS穩定性一般
126https://ip.ws.126.net/ipqueryJS網易出品
hao123https://app.hao123.com/ipquery/getcity.php?rtype=2JSONP支援 callback 參數

前端直連範例(以騰訊、新浪、搜狐為例)

1. 騰訊 IP API

<script src="https://fw.qq.com/ipaddress"></script>
<script>
document.write('你的 IP:' + IPData[0] + ',來自:' + IPData[2] + IPData[3]);
</script>

2. 新浪 IP API(資訊最豐富)

<script src="https://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js"></script>
<script>
if (typeof remote_ip_info !== 'undefined' && remote_ip_info.ret === 1) {
    console.log('IP:', remote_ip_info.start);
    console.log('國家:', unescape(remote_ip_info.country));
    console.log('省份:', unescape(remote_ip_info.province));
    console.log('城市:', unescape(remote_ip_info.city));
    console.log('ISP:', unescape(remote_ip_info.isp));
}
</script>

3. 搜狐 IP API(最輕量)

<script src="https://pv.sohu.com/cityjson"></script>
<script>
console.log('IP:', returnCitySN.cip);
console.log('地區代碼:', returnCitySN.cid);
console.log('地區名稱:', returnCitySN.cname);
</script>

生產環境最佳實踐

  • HTTPS 強制:現代瀏覽器封鎖混合內容,優先選支援 HTTPS 的介面(如 https://api.ip.sb/geoip、https://ipapi.co/json/)。
  • 備援機制:採用 Promise.allSettled 並行請求多家 API,取第一個成功結果。
  • 快取策略:IP 歸屬地變動極低,前端可 localStorage 快取 24 小時,減少外部請求。
  • 隱私合規:依 GDPR/個資法告知用戶並取得同意後再呼叫。

現代替代方案(推薦)

// 純 JSON、支援 HTTPS、無 callback 參數、CORS 開放
fetch('https://ipapi.co/json/')
  .then(r => r.json())
  .then(data => console.log(data.ip, data.city, data.country_name));

上述服務免費額度每日 1,000 次,商業專案建議自建 MaxMind GeoLite2 資料庫或採用付費 API(ipinfo.io、ipgeolocation.io 等)。

copyright © 萬盛學電腦網 all rights reserved