一个获取远程客户端真实IP的例子
一个获取远程客户端真实IP的例子(仅供参考):
View Code
1 public static string GetIP()
2 {
3 string strIP = string.Empty;
4 //获取代理用户真实IP地址
5 //如果不是代理用户将返回null
6 strIP = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
7 if (string.IsNullOrEmpty(strIP))
8 {
9 //获取远程客户端请求的IP地址
10 strIP = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
11 }
12 if (string.IsNullOrEmpty(strIP))
13 {
14 //获取远程客户端的IP主机地址
15 strIP = HttpContext.Current.Request.UserHostAddress;
16 }
17 if (string.IsNullOrEmpty(strIP) && !IsIP(strIP))
18 {
19 return "0.0.0.0";
20 }
21
22 return strIP;
23 }
24
25 public static bool IsIP(string strIP)
26 {
27 //验证IP格式
28 return Regex.IsMatch(strIP, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
29 }
2 {
3 string strIP = string.Empty;
4 //获取代理用户真实IP地址
5 //如果不是代理用户将返回null
6 strIP = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
7 if (string.IsNullOrEmpty(strIP))
8 {
9 //获取远程客户端请求的IP地址
10 strIP = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
11 }
12 if (string.IsNullOrEmpty(strIP))
13 {
14 //获取远程客户端的IP主机地址
15 strIP = HttpContext.Current.Request.UserHostAddress;
16 }
17 if (string.IsNullOrEmpty(strIP) && !IsIP(strIP))
18 {
19 return "0.0.0.0";
20 }
21
22 return strIP;
23 }
24
25 public static bool IsIP(string strIP)
26 {
27 //验证IP格式
28 return Regex.IsMatch(strIP, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
29 }
-------------------------------------------------------学习交流 欢迎指摘----------------------------------------------------------