萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

.NET 透過 ip138 取得本機公網 IP 位址

伺服器位於 NAT 或負載平衡器後方時,Request.UserHostAddress 只能取得內網或代理 IP。可呼叫外部服務 (如 ip138) 解析回傳頁面中的公網 IP。

完整工具類

using System;
using System.Net;
using System.Text.RegularExpressions;

public static class PublicIpHelper
{
    private const string Ip138Url = "https://iframe.ip138.com/ic.asp"; // 注意:HTTP 非 HTTPS
    private static readonly Regex IpRegex = new Regex(@"\[(?<ip>\d+\.\d+\.\d+\.\d+)\]", RegexOptions.Compiled);

    public static string GetPublicIp(int timeoutMs = 5000)
    {
        try
        {
            using (var client = new WebClient())
            {
                client.Encoding = System.Text.Encoding.GetEncoding("gb2312"); // ip138 回傳 GB2312
                client.Headers["User-Agent"] = "Mozilla/5.0";
                var html = client.DownloadString(Ip138Url);
                var match = IpRegex.Match(html);
                return match.Success ? match.Groups["ip"].Value : null;
            }
        }
        catch (Exception ex)
        {
            // 記錄 Log,回傳 null 讓呼叫端決定 fallback
            return null;
        }
    }

    /// <summary> 非同步版本 (建議在 ASP.NET Core / .NET 4.5+ 使用) </summary>
    public static async System.Threading.Tasks.Task<string> GetPublicIpAsync()
    {
        using (var http = new HttpClient())
        {
            http.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0");
            var html = await http.GetStringAsync(Ip138Url);
            var match = IpRegex.Match(html);
            return match.Success ? match.Groups["ip"].Value : null;
        }
    }
}

使用範例

string ip = PublicIpHelper.GetPublicIp();
if (ip != null)
    Console.WriteLine($"公網 IP:{ip}");
else
    Console.WriteLine("取得失敗,改用本機 IP 或預設值");

替代免費 API (支援 HTTPS、JSON、無編碼問題)

服務端點回傳格式頻率限制
ipifyhttps://api.ipify.org?format=json{"ip":"..."}無限制 (合理使用)
ipinfo.iohttps://ipinfo.io/json{"ip":"...", "city":"...", ...}免費 50k/月
ifconfig.mehttps://ifconfig.me/ip純文字 IP無限制
// 以 ipify 為例
public static async Task<string> GetIpViaIpifyAsync()
{
    using (var http = new HttpClient())
    {
        var json = await http.GetStringAsync("https://api.ipify.org?format=json");
        return System.Text.Json.JsonDocument.Parse(json).RootElement.GetProperty("ip").GetString();
    }
}

注意事項

  • ip138 為 HTTP 且回傳 GB2312,安全性與相容性較差,建議改用 HTTPS JSON API。
  • 外部服務可能失效或封鎖,生產環境請實作 快取 (如 5 分鐘) 並備援多個 API。
  • 若伺服器有多張網卡/多重出口 IP,結果可能非預期出口 IP,需配合網路架構驗證。
copyright © 萬盛學電腦網 all rights reserved