个人网站地址:
ASP.NET 的IP帮助类
在Web开发中会出现需要调用客户IP的方法; 一般调用方法就是使用Request函数来获取;
代码如下
HttpContext.Current.Request.UserHostAddress.ToString()
不过想要放获取方法变得高大上一点的话还是得需要自己写一个IP帮助类;以下是代码
public class IPHelp{#region IP地址互转整数////// 将IP地址转为整数形式/// ///整数 public static long IP2Long(IPAddress ip){int x = 3;long o = 0;foreach (byte f in ip.GetAddressBytes()){o += (long)f << 8 * x--;}return o;}////// 将整数转为IP地址/// ///IP地址 public static IPAddress Long2IP(long l){byte[] b = new byte[4];for (int i = 0; i < 4; i++){b[3 - i] = (byte)(l >> 8 * i & 255);}return new IPAddress(b);}#endregion////// 获得客户端IP/// public static string ClientIP{get{bool isErr = false;string ip = "127.0.0.1";try{ string[] temp;if (HttpContext.Current.Request.ServerVariables["HTTP_X_ForWARDED_For"] == null)ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();elseip = HttpContext.Current.Request.ServerVariables["HTTP_X_ForWARDED_For"].ToString();if (ip.Length > 15)isErr = true;else{temp = ip.Split('.');if (temp.Length == 4){for (int i = 0; i < temp.Length; i++){if (temp[i].Length > 3) isErr = true;}}elseisErr = true;}}catch { isErr = false; } if (isErr)return "1.1.1.1";elsereturn ip;}}}
需要调用来源IP的时候直接 调用ClientIP属性即可
var ipaddr =IPHelp.ClientIP;
代码下载地址:
原文地址: