获取客户端真实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]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
34         }
35 

 

posted @ 2018-09-05 17:00  秒杀5S  阅读(879)  评论(0编辑  收藏  举报