Visual C# IP相關操作類,獲得當前客戶端IP,判斷IP格式,也就是檢測是否是IP地址,一些關於IP的基本操作,歡迎C#新手參考:
01///
02/// 獲得當前頁面客戶端的IP
03///
04/// 當前頁面客戶端的IP
05public static string GetIP()
06{
07 string result = String.Empty;
08 result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
09 if (null == result || result == String.Empty)
10 {
11 result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
12 }
13 if (null == result || result == String.Empty)
14 {
15 result = HttpContext.Current.Request.UserHostAddress;
16 }
17 if (null == result || result == String.Empty || !IsIP(result))
18 {
19 return "0.0.0.0";
20 }
21 return result;
22}
23///
24/// 是否為ip
25///
26///
27///
28public static bool IsIP(string ip)
29{
30 return Regex.IsMatch(ip, @"^((2[0-4]d|25[0-5]|[01]?dd?).){3}(2[0-4]d|25[0-5]|[01]?dd?)$");
31}