萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

C# 呼叫有道 IP 地址查詢介面:XML 解析實戰

介面說明

有道提供簡單的 IP 查詢 HTTP 介面:

https://www.youdao.com/smartresult-xml/search.s?type=ip&q={IP地址}

回傳 XML 格式(GBK 編碼):

<?xml version="1.0" encoding="gbk"?>
<smartresult>
  <product type="ip">
    <ip>60.223.233.226</ip>
    <location>山西省朔州市 網通</location>
  </product>
</smartresult>

完整實作程式碼

public static string GetIpLocation(string ip)
{
    string url = $"https://www.youdao.com/smartresult-xml/search.s?type=ip&q={ip}";
    string location = "";

    using (XmlReader reader = XmlReader.Create(url))
    {
        while (reader.Read())
        {
            if (reader.NodeType == XmlNodeType.Text)
            {
                string val = reader.Value.Trim();
                if (val != ip) // 排除 IP 本身,剩下的就是地址
                {
                    location = val;
                    break;
                }
            }
        }
    }
    return location;
}

關鍵技術點

  • XmlReader.Create(url):直接從 HTTP 串流建立讀取器,記憶體效率高。
  • XmlNodeType.Text:只關注文字節點,忽略元素標籤。
  • 邏輯判斷 val != ip:利用回傳 XML 結構特性(先出現 IP,再出現地址),簡單過濾得到地址。
  • 編碼處理:XML 宣告為 GBK,XmlReader 會自動依宣告解碼,無需手動指定。

擴充建議

  1. 加入快取機制(如 MemoryCache),避免重複查詢同一 IP。
  2. 封裝為非同步方法 Task<string> GetIpLocationAsync(string ip),避免阻塞 UI 執行緒。
  3. 異常處理:網路錯誤、XML 格式變更、IP 格式驗證。
  4. 若需高併發,考慮改用離線 IP 資料庫(如 GeoIP2、ip2region)。

注意事項

  • 此為非官方公開 API,穩定性與頻率限制無保證,生產環境建議使用商業 IP 地址庫。
  • HTTP 非 HTTPS,傳輸過程可被竄改,敏感場景請評估風險。
copyright © 萬盛學電腦網 all rights reserved