C#获得当前页面客户端的真实IP

并且可以提取开启代理/cdn服务后的客户端真实IP


IPHelper帮助类库源码


/// <summary>
/// 开发团队:JsonsTeam
/// 官方主页:http://www.jsons.cn
/// </summary>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace JsonsTeam.Helper
{
    public class IPHelper
    {
        /// <summary>
        /// C#获得当前页面客户端的真实IP
        /// 可以提取开启代理/cdn服务后的客户端真实IP
        /// </summary>
        /// <returns>当前页面客户端的真实IP</returns>
        public static string GetTrueIP()
        {
            string ip = string.Empty;
            string X_Forwarded_For = HttpContext.Current.Request.Headers["X-Forwarded-For"];
            if (!string.IsNullOrWhiteSpace(X_Forwarded_For))
            {
                ip = X_Forwarded_For;
            }
            else
            {
                string CF_Connecting_IP = HttpContext.Current.Request.Headers["CF-Connecting-IP"];
                if (!string.IsNullOrWhiteSpace(CF_Connecting_IP))
                {
                    ip = CF_Connecting_IP;
                }
                else
                {
                    //没开启代理 正常获取ip
                    ip = HttpContext.Current.Request.UserHostAddress;
                }
            }
            return ip;
        }
    }
}


原文链接:C#获得当前页面客户端的真实IP