有道提供簡單的 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,再出現地址),簡單過濾得到地址。XmlReader 會自動依宣告解碼,無需手動指定。MemoryCache),避免重複查詢同一 IP。Task<string> GetIpLocationAsync(string ip),避免阻塞 UI 執行緒。