透過 `Request.ServerVariables` 依序檢查:`HTTP_X_FORWARDED_FOR` (Proxy 鏈) → `HTTP_X_REAL_IP` (Nginx) → `REMOTE_ADDR` (直接連線)。取第一個非私有 IP 作為真實客戶端 IP。
using System;
using System.Net;
using System.Web;
public static class ClientIpHelper
{
private static readonly string[] ProxyHeaders =
{
"HTTP_X_FORWARDED_FOR", // 標準 Proxy 標頭,可能包含多個 IP (client, proxy1, proxy2...)
"HTTP_X_REAL_IP", // Nginx proxy_set_header X-Real-IP
"HTTP_CLIENT_IP", // 部分 Proxy 使用
"HTTP_X_CLUSTER_CLIENT_IP", // AWS ALB / Azure Front Door
"HTTP_FORWARDED_FOR", // RFC 7239 Forwarded 標頭舊格式
"HTTP_FORWARDED" // RFC 7239 Forwarded: for="..."
};
/// 取得用戶端真實 IP (IPv4/IPv6)
public static string GetClientIp(HttpRequest request = null)
{
request ??= HttpContext.Current?.Request;
if (request == null) return "::1"; // 非 Web Context (背景工作) 回傳 localhost
foreach (var header in ProxyHeaders)
{
string value = request.ServerVariables[header];
if (!string.IsNullOrWhiteSpace(value))
{
// X-Forwarded-For 可能包含多個 IP,取最左邊 (原始客戶端)
string[] ips = value.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string ip in ips)
{
string trimmed = ip.Trim();
if (IsPublicIp(trimmed)) return trimmed;
}
}
}
// 回退至直接連線 IP
string remote = request.ServerVariables["REMOTE_ADDR"];
return IsPublicIp(remote) ? remote : "::1";
}
/// 判斷是否為公網 IP (排除私有/回環/鏈路本地)
private static bool IsPublicIp(string ipStr)
{
if (string.IsNullOrWhiteSpace(ipStr)) return false;
if (!IPAddress.TryParse(ipStr, out IPAddress ip)) return false;
// IPv4 私有範圍: 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, 127.0.0.0/8, 169.254.0.0/16
// IPv6: ::1 (loopback), fe80::/10 (link-local), fc00::/7 (unique local)
if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
byte[] bytes = ip.GetAddressBytes();
// 10.x.x.x
if (bytes[0] == 10) return false;
// 172.16.x.x - 172.31.x.x
if (bytes[0] == 172 && bytes[1] >= 16 && bytes[1] <= 31) return false;
// 192.168.x.x
if (bytes[0] == 192 && bytes[1] == 168) return false;
// 127.x.x.x (loopback)
if (bytes[0] == 127) return false;
// 169.254.x.x (APIPA)
if (bytes[0] == 169 && bytes[1] == 254) return false;
}
else if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6)
{
if (IPAddress.IsLoopback(ip)) return false;
byte[] bytes = ip.GetAddressBytes();
// fe80::/10 (link-local) -> 前 10 bits = 1111 1110 10
if ((bytes[0] == 0xFE) && ((bytes[1] & 0xC0) == 0x80)) return false;
// fc00::/7 (unique local) -> 前 7 bits = 1111 110
if ((bytes[0] & 0xFE) == 0xFC) return false;
}
return true;
}
}
// Web Forms / MVC Controller
string clientIp = ClientIpHelper.GetClientIp();
Log.Info($"用戶 {clientIp} 存取 {Request.RawUrl}");
// 全域記錄攔截器 (Global.asax / Middleware)
public class IpLoggingModule : IHttpModule
{
public void Init(HttpApplication app)
{
app.BeginRequest += (s, e) =>
{
var ctx = ((HttpApplication)s).Context;
ctx.Items["ClientIp"] = ClientIpHelper.GetClientIp(ctx.Request);
};
}
public void Dispose() { }
}
| 架構 | 關鍵標頭 | 設定提醒 |
|---|---|---|
| Nginx 反向代理 | X-Real-IP, X-Forwarded-For | `proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;` |
| Azure Application Gateway / Front Door | X-Forwarded-For, X-Cluster-Client-IP | 啟用「保留原始用戶端 IP」設定 |
| AWS ALB / NLB | X-Forwarded-For | ALB 預設附加,NLB 需啟用 Proxy Protocol v2 |
| Kubernetes Ingress (NGINX/Traefik) | X-Forwarded-For | 確認 `externalTrafficPolicy: Local` 保留來源 IP |
| Cloudflare | CF-Connecting-IP | 優先讀取 `HTTP_CF_CONNECTING_IP`,再回退 X-Forwarded-For |