C# 获取客户端IP

  • A+
所属分类:ASP.NET

C# 获取客户端IP

直接贴代码方便备查

  1. /// <summary>  
  2. /// 获取客户端IP  
  3. /// </summary>  
  4. /// <returns></returns>  
  5. public string GetIp()  
  6. {  
  7.     string Ip = "未获取用户IP";  
  8.     try  
  9.     {  
  10.         if (System.Web.HttpContext.Current == null || System.Web.HttpContext.Current.Request == null || System.Web.HttpContext.Current.Request.ServerVariables == null)  
  11.             return "";  
  12.         string CustomerIP = "";  
  13.         CustomerIP = System.Web.HttpContext.Current.Request.Headers["Cdn-Src-Ip"];  
  14.         if (!string.IsNullOrEmpty(CustomerIP))  
  15.         {  
  16.             return CustomerIP;  
  17.         }  
  18.         CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];  
  19.         if (!String.IsNullOrEmpty(CustomerIP))  
  20.             return CustomerIP;  
  21.         if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)  
  22.         {  
  23.             CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];  
  24.             if (CustomerIP == null)  
  25.                 CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];  
  26.         }  
  27.         else  
  28.         {  
  29.             CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];  
  30.         }  
  31.         if (string.Compare(CustomerIP, "unknown"true) == 0)  
  32.             return System.Web.HttpContext.Current.Request.UserHostAddress;  
  33.         return CustomerIP;  
  34.     }  
  35.     catch  
  36.     {  
  37.         Ip = null;  
  38.     }  
  39.     return Ip;  
  40. }  
钰玺

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: