获取用户真实IP地址

来源:互联网 发布:防火墙端口开放 编辑:程序博客网 时间:2024/05/17 09:03

获取用户真实IP地址,本地测试没用的,必须发布后测试。

/// <summary>        /// 获取用户真实IP地址        /// </summary>        /// <returns></returns>        public static string GetUserIp()        {            string ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];            if (ip == null || ip.Length == 0 || ip.ToLower().IndexOf("unknown") > -1)            {                ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];            }            else            {                if (ip.IndexOf(',') > -1)                {                    ip = ip.Substring(0, ip.IndexOf(','));                }                if (ip.IndexOf(';') > -1)                {                    ip = ip.Substring(0, ip.IndexOf(';'));                }            }            Regex regex = new Regex("[^0-9.]");            if (ip == null || ip.Length == 0 || regex.IsMatch(ip))            {                ip = HttpContext.Current.Request.UserHostAddress;                if (ip == null || ip.Length == 0 || regex.IsMatch(ip))                {                    ip = "0.0.0.0";                }            }            return ip;        }


原创粉丝点击