您的位置:首页 > 编程语言 > ASP

ASP.NET获取真实IP

2010-04-02 13:22 239 查看
此方法有问题,还没来得及找问题出在哪儿,估计get那儿肯定是不对了
代码

1 /// <summary>
2 /// 取得客户端真实IP。如果有代理则取第一个非内网地址
3 /// </summary>
4 public static string IPAddress
5 {
6 get
7 {
8 string result = String.Empty;
9
10 result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
11 if (result != null && result != String.Empty)
12 {
13 //可能有代理
14 if (result.IndexOf(".") == -1) //没有“.”肯定是非IPv4格式
15 result = null;
16 else
17 {
18 if (result.IndexOf(",") != -1)
19 {
20 //有“,”,估计多个代理。取第一个不是内网的IP。
21 result = result.Replace(" ", "").Replace("'", "");
22 string[] temparyip = result.Split(",;".ToCharArray());
23 for (int i = 0; i < temparyip.Length; i++)
24 {
25 if (IsIPAddress(temparyip[i])
26 && temparyip[i].Substring(0, 3) != "10."
27 && temparyip[i].Substring(0, 7) != "192.168"
28 && temparyip[i].Substring(0, 7) != "172.16.")
29 {
30 return temparyip[i]; //找到不是内网的地址
31 }
32 }
33 }
34 else if (IsIPAddress(result)) //代理即是IP格式
35 return result;
36 else
37 result = null; //代理中的内容 非IP,取IP
38 }
39
40 }
41
42 string IpAddress = (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null && HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != String.Empty) ? HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] : HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
43
44
45
46 if (null == result || result == String.Empty)
47 result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
48
49 if (result == null || result == String.Empty)
50 result = HttpContext.Current.Request.UserHostAddress;
51
52 return result;
53 }
54 }
55 #region bool IsIPAddress(str1) 判断是否是IP格式
56 /**/
57 /// <summary>
58 /// 判断是否是IP地址格式 0.0.0.0
59 /// </summary>
60 /// <param name="str1">待判断的IP地址</param>
61 /// <returns>true or false</returns>
62 public static bool IsIPAddress(string str1)
63 {
64 if (str1 == null || str1 == string.Empty || str1.Length < 7 || str1.Length > 15) return false;
65
66 string regformat = @"^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$";
67
68 Regex regex = new Regex(regformat, RegexOptions.IgnoreCase);
69 return regex.IsMatch(str1);
70 }
71 #endregion
72
73
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: