c# 獲取客戶端IP

薛定諤家的貓發表於2018-09-27
        /// <summary>
        /// 獲得當前頁面客戶端的IP
        /// </summary>
        /// <returns>當前頁面客戶端的IP</returns>
        public static string GetIP()
        {
            try
            {
                string result = String.Empty;

                result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                if (string.IsNullOrEmpty(result))
                {
                    result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                }

                if (string.IsNullOrEmpty(result))
                {
                    result = HttpContext.Current.Request.UserHostAddress;
                }

                if (string.IsNullOrEmpty(result) || !Utils.IsIP(result))
                {
                    return "127.0.0.1";
                }

                return result;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.Write(ex.Message);
                return HttpContext.Current.Request.UserHostAddress;
            }
        }

 

相關文章