許多系統需依據使用者 IP 顯示所在城市、國家,以提供在地化內容或安全稽核。雖有商用 GeoIP 資料庫 (MaxMind、IP2Location),但若專案預算有限或僅需簡易查詢,透過公開查詢網站 (如 ip138.com、cz88.net) 解析 HTML 回應即可快速實作。
https://www.ip138.com/ips8.asp 取得訪客公網 IP 及國家資訊。https://www.cz88.net/ip/?ip= 查詢省市細節。using System;
using System.Net;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
public class IpLocationService
{
private readonly WebClient _client = new WebClient { Encoding = Encoding.Default };
///
/// 取得完整 IP 位址、國家、省市資訊
///
public string GetIpDetails()
{
// 1. 取得 IP 與國家
string html = _client.DownloadString("https://www.ip138.com/ips8.asp");
// 正則擷取 ...
之間的內容
Match m = Regex.Match(html, @"(?<=)[^<]*?(?=
)");
if (!m.Success) return "查詢失敗";
string block = m.Value;
// 擷取 IP
Match ipMatch = Regex.Match(block, @"((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)");
string ip = ipMatch.Success ? ipMatch.Value : "未知";
// 擷取國家 (最後一個「:」之後)
int idx = block.LastIndexOf(":");
string country = idx >= 0 ? block.Substring(idx + 1).Trim() : "未知";
// 2. 查詢省市
string city = GetCityByIp(ip);
return $"IP:{ip} 國家:{country} 省市:{city}";
}
///
/// 根據 IP 取得省市
///
private string GetCityByIp(string ip)
{
string url = $"https://www.cz88.net/ip/?ip={ip}";
string html = _client.DownloadString(url);
Match m = Regex.Match(html, @"(?<=).*?(?=)");
if (!m.Success) return "未知";
// 回傳格式通常為 "中國 廣東 廣州 電信",取第一段作為省市
return m.Value.Split(' ')[0];
}
}
兩個目標網站均使用 GB2312/GBK 編碼,WebClient.Encoding = Encoding.Default (或 Encoding.GetEncoding("GB2312")) 可自動解碼,避免中文亂碼。
(?<=...) 正向後顧斷言:定位起始標籤但不納入匹配結果。(?=...) 正向前顧斷言:定位結束標籤但不納入匹配結果。生產環境建議加入:
_client.Timeout = 5000)| 方案 | 優點 | 缺點 |
|---|---|---|
| MaxMind GeoLite2 (本地 MMDB) | 離線、高效能、免費版每月更新 | 需部署資料庫檔案、精度略低於付費版 |
| IP2Location / IPinfo.io API | 精度高、支援 HTTPS、豐富欄位 (ISP、時區、郵遞區號) | 付費、受 API 配額限制 |
| 自建 IP 段對照表 | 完全可控、無外部依賴 | 維護成本高、資料易過期 |
透過簡單的 HTTP 請求與正則解析,即可在無預算專案中快速獲得 IP 歸屬地資訊。但需注意:公開查詢站點可能變更頁面結構、限制頻率或停止服務,正式上線建議改用本地資料庫或付費 API 以保障穩定性。