• 获取客户端真实ip地址(无视代理)


     1 /// <summary>
     2         /// 获取客户端IP地址(无视代理)
     3         /// </summary>
     4         /// <returns>若失败则返回回送地址</returns>
     5         public static string GetHostAddress()
     6         {
     7             string userHostAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
     8             if (string.IsNullOrEmpty(userHostAddress))
     9             {
    10                 if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
    11                     userHostAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString().Split(',')[0].Trim();
    12             }
    13             if (string.IsNullOrEmpty(userHostAddress))
    14             {
    15                 userHostAddress = HttpContext.Current.Request.UserHostAddress;
    16             }
    17 
    18             //最后判断获取是否成功,并检查IP地址的格式(检查其格式非常重要)
    19             if (!string.IsNullOrEmpty(userHostAddress) && IsIP(userHostAddress))
    20             {
    21                 return userHostAddress;
    22             }
    23             return "127.0.0.1";
    24         }
    25 
    26         /// <summary>
    27         /// 检查IP地址格式
    28         /// </summary>
    29         /// <param name="ip"></param>
    30         /// <returns></returns>
    31         public static bool IsIP(string ip)
    32         {
    33             return System.Text.RegularExpressions.Regex.IsMatch(ip, @"^((2[0-4]d|25[0-5]|[01]?dd?).){3}(2[0-4]d|25[0-5]|[01]?dd?)$");
    34         }
    35 
  • 相关阅读:
    性能优化与使用Block实现数据回传(3)
    封装思想和抽取(2)
    磁盘缓存的计算与清理(1)
    滑动返回的延伸(全局滑动返回功能)
    滑动返回功能被覆盖的解决思路
    OC之类与对象
    OC之OC与C的比较
    OC之知识储备篇
    C语言之总结3
    C语言总结2
  • 原文地址:https://www.cnblogs.com/miaosha5s/p/9593179.html
Copyright © 2020-2023  润新知