伺服器位於 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 或預設值");
| 服務 | 端點 | 回傳格式 | 頻率限制 |
|---|---|---|---|
| ipify | https://api.ipify.org?format=json | {"ip":"..."} | 無限制 (合理使用) |
| ipinfo.io | https://ipinfo.io/json | {"ip":"...", "city":"...", ...} | 免費 50k/月 |
| ifconfig.me | https://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();
}
}