MVC中获取客户端IPV4地址帮助类


using System;
using System.Web;

namespace CustPoWeb
{
    /// 
    ///     MVC中获取客户端IPV4地址帮助类
    ///     LDH @ 2021-12-31
    /// 
    public static class IpHelper
    {
        /// 
        ///     获取Web客户端IP地址
        ///     LDH @ 2021-12-31
        /// 
        /// 
        public static string GetWebClientIp()
        {
            var userIP = "未获取用户IP";

            try
            {
                if (HttpContext.Current == null) return "";

                var customerIp = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

                if (!string.IsNullOrEmpty(customerIp)) return customerIp;

                if (HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
                {
                    customerIp = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

                    if (customerIp == null)
                        customerIp = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                }
                else
                {
                    customerIp = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                }

                if (string.Compare(customerIp, "unknown", StringComparison.OrdinalIgnoreCase) == 0
                    || string.IsNullOrEmpty(customerIp))
                    return HttpContext.Current.Request.UserHostAddress;

                return customerIp;
            }
            catch
            {
                // ignored
            }

            return userIP;
        }
    }
}