首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> ASP.NET 基礎

C# 透過 IP 地址查詢地理位置:從網頁爬蟲到實戰封裝

     編輯:ASP.NET 基礎

需求背景

許多系統需依據使用者 IP 顯示所在城市、國家,以提供在地化內容或安全稽核。雖有商用 GeoIP 資料庫 (MaxMind、IP2Location),但若專案預算有限或僅需簡易查詢,透過公開查詢網站 (如 ip138.com、cz88.net) 解析 HTML 回應即可快速實作。

核心思路

  1. 呼叫 https://www.ip138.com/ips8.asp 取得訪客公網 IP 及國家資訊。
  2. 以正則表達式擷取 IP 與國家字串。
  3. 將 IP 送至 https://www.cz88.net/ip/?ip= 查詢省市細節。
  4. 整合回傳格式化字串。

完整實作代碼

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]; } }

關鍵技術點解析

1. 編碼處理

兩個目標網站均使用 GB2312/GBK 編碼,WebClient.Encoding = Encoding.Default (或 Encoding.GetEncoding("GB2312")) 可自動解碼,避免中文亂碼。

2. 正則表達式設計

  • (?<=...) 正向後顧斷言:定位起始標籤但不納入匹配結果。
  • (?=...) 正向前顧斷言:定位結束標籤但不納入匹配結果。
  • IP 正則採用標準四段式驗證,確保擷取精準。

3. 例外與容錯

生產環境建議加入:

  • 請求逾時設定 (_client.Timeout = 5000)
  • 重試機制 (Polly 或簡單迴圈)
  • 快取機制 (MemoryCache) 減少重複查詢同一 IP
  • 降級策略:若外部站點不可用,回傳本地 GeoIP 資料庫結果或預設值

進階替代方案

方案優點缺點
MaxMind GeoLite2 (本地 MMDB)離線、高效能、免費版每月更新需部署資料庫檔案、精度略低於付費版
IP2Location / IPinfo.io API精度高、支援 HTTPS、豐富欄位 (ISP、時區、郵遞區號)付費、受 API 配額限制
自建 IP 段對照表完全可控、無外部依賴維護成本高、資料易過期

總結

透過簡單的 HTTP 請求與正則解析,即可在無預算專案中快速獲得 IP 歸屬地資訊。但需注意:公開查詢站點可能變更頁面結構、限制頻率或停止服務,正式上線建議改用本地資料庫或付費 API 以保障穩定性。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved