根據 IP 定位地理位置是個性化服務、風控、統計分析的基礎需求。本文展示如何在 Node.js 與 PHP 中呼叫新浪 IP 查詢介面 (int.dpool.sina.com.cn),解析 JSON 回應,獲取國家、省份、城市、ISP 等資訊,並討論生產環境的可靠性考量。
https://int.dpool.sina.com.cn/iplookup/iplookup.phpformat=json、ip=目標IP (選填,預設為請求端 IP)| 欄位 | 說明 | 範例 |
|---|---|---|
ret | 狀態碼:1=成功,0=失敗 | 1 |
start/end | IP 範圍 | 49.68.0.0 / 49.68.255.255 |
country | 國家 | 中國 |
province | 省份 | 江蘇 |
city | 城市 | 徐州 |
district | 區/縣 | (空) |
isp | 網路服務提供商 | 電信/聯通/移動/鐵通/教育網 |
type/desc | 類型/描述 | (通常為空) |
const http = require('http');
const { promisify } = require('util');
function getIpInfo(ip) {
return new Promise((resolve, reject) => {
const url = `https://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=${encodeURIComponent(ip)}`;
http.get(url, (res) => {
if (res.statusCode !== 200) {
return reject(new Error(`HTTP ${res.statusCode}`));
}
let raw = '';
res.on('data', chunk => raw += chunk);
res.on('end', () => {
try {
const data = JSON.parse(raw);
if (data.ret === 1) resolve(data);
else reject(new Error('查詢失敗:' + JSON.stringify(data)));
} catch (e) {
reject(new Error('JSON 解析失敗:' + e.message));
}
});
}).on('error', reject);
});
}
// 使用範例 (async/await)
(async () => {
try {
const info = await getIpInfo('220.181.111.85'); // 百度爬蟲 IP
console.log(`城市: ${info.city}`);
console.log(`完整資訊:`, info);
} catch (err) {
console.error('查詢錯誤:', err.message);
}
})();
async function getIpInfoFetch(ip) {
const url = `https://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=${encodeURIComponent(ip)}`;
const res = await fetch(url);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = await res.json();
if (data.ret !== 1) throw new Error('查詢失敗');
return data;
}
<?php
function getIpInfo($ip) {
$url = "https://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=" . urlencode($ip);
$context = stream_context_create([
'http' => [
'timeout' => 5, // 秒
'user_agent' => 'Mozilla/5.0 (compatible; IPGeoBot/1.0)'
]
]);
$response = @file_get_contents($url, false, $context);
if ($response === false) {
return ['error' => '請求失敗'];
}
$data = json_decode($response, true);
if (json_last_error() !== JSON_ERROR_NONE) {
return ['error' => 'JSON 解析失敗'];
}
return $data;
}
// 使用
$ip = '220.181.111.85';
$result = getIpInfo($ip);
if (isset($result['error'])) {
echo "錯誤: " . $result['error'];
} else {
echo "城市: " . $result['city'] . "\n";
print_r($result);
}
?>
| 風險 | 影響 | 緩解策略 |
|---|---|---|
| 第三方介面不穩定/停止服務 | 功能完全失效 | 備援多個介面 (ip-api.com, ipinfo.io, 高德、騰訊位置服務) |
| HTTP 明文傳輸 | 資料竊聽、中間人攻擊 | 改用 HTTPS 付費服務 |
| 頻率限制 | 大量查詢被封禁 | 本地快取 (Redis)、批次查詢、自建 IP 庫 |
| 準確度限制 | 僅能精確到城市/ISP | 結合 GPS、WiFi 定位、用戶授權精確定位 |
| 跨境/VPN/代理 IP | 定位不準 | 風控結合裝置指紋、行為分析 |
ip2region、GeoLite2 (MaxMind)、IPIP.net 等離線資料庫// ip2region Node.js 範例 (需安裝 ip2region 包)
const { search } = require('ip2region');
const result = search('220.181.111.85');
// { region: '中国|0|江苏|徐州|电信', ... }
IpGeoProvider 介面,支援多供應商切換、快取、降級IP 定位是「概率性」而非「確定性」資訊,設計系統時務必考慮誤差與不可用情境。