首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> ASP.NET 基礎

取得客戶端 IP 位址:C# 與 VB.NET 完整實作碼

     編輯:ASP.NET 基礎

核心邏輯說明

由於 Proxy、Load Balancer、CDN 等中介層存在,單純讀取 Request.UserHostAddress 可能取得中介伺服器 IP 而非真實客戶端 IP。標準做法依序檢查:

  1. HTTP_X_FORWARDED_FOR 標頭(可能包含多個 IP,取第一個)
  2. HTTP_CLIENT_IP 標頭
  3. REMOTE_ADDR 伺服器變數

C# 實作

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;
}

VB.NET 實作

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}";
    // 記錄稽核日誌、風控判斷、地理位置查詢等
}

進階考量

場景處理建議
多層 ProxyX-Forwarded-For 可能包含鏈路 IP,需配合基礎設施團隊確認信任 Proxy 清單
IPv6 環境回傳格式如 ::ffff:192.168.1.1,需解析相容
雲端部署AWS ALB、Azure Front Door、Cloudflare 等有專屬標頭(如 CF-Connecting-IP),優先使用
安全性標頭可偽造,關鍵業務(登入、支付)需結合裝置指紋、行為分析等多因子驗證

圖示參考

C# 程式碼截圖:

C# 取得 Client IP 程式碼

VB.NET 程式碼截圖:

VB.NET 取得 Client IP 程式碼
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved