由於 Proxy、Load Balancer、CDN 等中介層存在,單純讀取 Request.UserHostAddress 可能取得中介伺服器 IP 而非真實客戶端 IP。標準做法依序檢查:
HTTP_X_FORWARDED_FOR 標頭(可能包含多個 IP,取第一個)HTTP_CLIENT_IP 標頭REMOTE_ADDR 伺服器變數public static string GetClientIP()
{
string ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (!string.IsNullOrEmpty(ip))
{
// 可能包含多個 IP:client, proxy1, proxy2... 取第一個
string[] ips = ip.Split(',');
return ips[0].Trim();
}
ip = HttpContext.Current.Request.ServerVariables["HTTP_CLIENT_IP"];
if (!string.IsNullOrEmpty(ip)) return ip;
return HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]
?? HttpContext.Current.Request.UserHostAddress;
}
Public Shared Function GetClientIP() As String
Dim ip As String = HttpContext.Current.Request.ServerVariables("HTTP_X_FORWARDED_FOR")
If Not String.IsNullOrEmpty(ip) Then
Dim ips() As String = ip.Split(","c)
Return ips(0).Trim()
End If
ip = HttpContext.Current.Request.ServerVariables("HTTP_CLIENT_IP")
If Not String.IsNullOrEmpty(ip) Then Return ip
Return HttpContext.Current.Request.ServerVariables("REMOTE_ADDR")
?? HttpContext.Current.Request.UserHostAddress
End Function
protected void Page_Load(object sender, EventArgs e)
{
string clientIP = GetClientIP();
lblIP.Text = $"客戶端 IP:{clientIP}";
// 記錄稽核日誌、風控判斷、地理位置查詢等
}
| 場景 | 處理建議 |
|---|---|
| 多層 Proxy | X-Forwarded-For 可能包含鏈路 IP,需配合基礎設施團隊確認信任 Proxy 清單 |
| IPv6 環境 | 回傳格式如 ::ffff:192.168.1.1,需解析相容 |
| 雲端部署 | AWS ALB、Azure Front Door、Cloudflare 等有專屬標頭(如 CF-Connecting-IP),優先使用 |
| 安全性 | 標頭可偽造,關鍵業務(登入、支付)需結合裝置指紋、行為分析等多因子驗證 |
C# 程式碼截圖:
VB.NET 程式碼截圖: