1 public class IPHelper 2 { 3 public static string GetVisitorsIPAddress() 4 { 5 string result = String.Empty; 6 7 result = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; 8 9 // 如果使用代理,获取真实IP 10 if (result != null && result.IndexOf(".") == -1) //没有“.”肯定是非IPv4格式 11 result = null; 12 else if (result != null) 13 { 14 if (result.IndexOf(",") != -1) 15 { 16 //有“,”,估计多个代理。取第一个不是内网的IP。 17 result = result.Replace(" ", "").Replace("'", ""); 18 string[] temparyip = result.Split(",;".ToCharArray()); 19 for (int i = 0; i < temparyip.Length; i++) 20 { 21 if (IsIPAddress(temparyip[i]) 22 && temparyip[i].Substring(0, 3) != "10." 23 && temparyip[i].Substring(0, 7) != "192.168" 24 && temparyip[i].Substring(0, 7) != "172.16.") 25 { 26 return temparyip[i]; //找到不是内网的地址 27 } 28 } 29 } 30 else if (IsIPAddress(result)) //代理即是IP格式 31 return result; 32 else 33 result = null; //代理中的内容 非IP,取IP 34 } 35 if (null == result || result == String.Empty) 36 result = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; 37 38 if (result == null || result == String.Empty) 39 result = System.Web.HttpContext.Current.Request.UserHostAddress; 40 41 return result; 42 } 43 44 /// <summary> 45 /// 判断是否是IP地址格式 0.0.0.0 46 /// </summary> 47 /// <param name="str1">待判断的IP地址</param> 48 /// <returns>true or false</returns> 49 private static bool IsIPAddress(string str1) 50 { 51 if (str1 == null || str1 == string.Empty || str1.Length < 7 || str1.Length > 15) return false; 52 53 string regformat = @"^d{1,3}[.]d{1,3}[.]d{1,3}[.]d{1,3}$"; 54 55 Regex regex = new Regex(regformat, RegexOptions.IgnoreCase); 56 return regex.IsMatch(str1); 57 } 58 }