zoukankan      html  css  js  c++  java
  • 获取客户端真实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 
  • 相关阅读:
    IO多路复用
    事件驱动模型
    协程
    进程
    py2与py3的编码问题
    Linux Centos7 网卡无法启动
    监控的法则
    如何优雅的采集activeMQ性能指标
    一分钟性能分析
    beta版 tomcat 应用监控指标
  • 原文地址:https://www.cnblogs.com/miaosha5s/p/9593179.html
Copyright © 2011-2022 走看看