c#獲取訪問者的真實IP地址以及所在地區(一)-------IP地址


 

在很多時候,我們需要獲取訪問者的iP地址,根據c#中自帶的類獲取的Ip地址其實並不是真正意義上的Ip.大部分獲取的都是代理Ip地址

直接貼代碼:

/// <summary>

        /// 獲取真ip
        /// </summary>
        /// <returns></returns>
        public string GetRealIP()
        {
            string result = String.Empty;
            result = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            //可能有代理 
            if (!string.IsNullOrWhiteSpace(result))
            {
                //沒有"." 肯定是非IP格式
                if (result.IndexOf(".") == -1)
                {
                    result = null;
                }
                else
                {
                    //有",",估計多個代理。取第一個不是內網的IP。
                    if (result.IndexOf(",") != -1)
                    {
                        result = result.Replace(" ", string.Empty).Replace("\"", string.Empty);
                        string[] temparyip = result.Split(",;".ToCharArray());
                        if (temparyip != null && temparyip.Length > 0)
                        {
                            for (int i = 0; i < temparyip.Length; i++)
                            {
                                //找到不是內網的地址
                                if (IsIPAddress(temparyip[i]) && temparyip[i].Substring(0, 3) != "10." && temparyip[i].Substring(0, 7) != "192.168" && temparyip[i].Substring(0, 7) != "172.16.")
                                {
                                    return temparyip[i];
                                }
                            }
                        }
                    }
                    //代理即是IP格式
                    else if (IsIPAddress(result))
                    {
                        return result;
                    }
                    //代理中的內容非IP
                    else
                    {
                        result = null;
                    }
                }
            }
            if (string.IsNullOrWhiteSpace(result))
            {
                result = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            }
            if (string.IsNullOrWhiteSpace(result))
            {
                result = System.Web.HttpContext.Current.Request.UserHostAddress;
            }
            return result;
        }


原文地址:https://www.zddblog.top/Home/Detail?art_id=Mjg=

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章