获取客户端IP主机地址。

 

 /// <summary>
        /// 获取客户端IP主机地址。
        /// </summary>
        /// <returns></returns>
        public static string GetIP()
        {
            HttpRequest request = HttpContext.Current.Request;
            string result = request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (string.IsNullOrEmpty(result))
            {
                result = request.ServerVariables["REMOTE_ADDR"];
            }
            if (string.IsNullOrEmpty(result))
            {
                result = request.UserHostAddress;
            }
            //最后判断获取是否成功,并检查IP地址的格式(检查其格式非常重要)
            string patten = @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$";
            if (!string.IsNullOrEmpty(result) && Regex.IsMatch(result, patten))
            {
                return result;
            }

            return "127.0.0.1";
        }

 

posted @ 2022-01-25 16:32  乌柒柒  阅读(41)  评论(0编辑  收藏  举报