
话不多说,请看代码:
/// <summary> /// 获取客户端IP /// </summary> /// <returns></returns> public static string GetClIEntIpAddress() { var httpContext = httpContext.Current; if (httpContext.Request.ServerVariables == null) { return null; } var clIEntIp = httpContext.Request.ServerVariables["http_X_FORWARDED_FOR"] ?? httpContext.Request.ServerVariables["REMOTE_ADDR"]; try { foreach (var hostAddress in Dns.GetHostAddresses(clIEntIp)) { if (hostAddress.AddressFamily == AddressFamily.InterNetwork) { return hostAddress.ToString(); } } foreach (var hostAddress in Dns.GetHostAddresses(Dns.GetHostname())) { if (hostAddress.AddressFamily == AddressFamily.InterNetwork) { return hostAddress.ToString(); } } } catch (Exception ex) { } return clIEntIp; } /// <summary> /// ip是否在ip空间内 /// </summary> /// <param name="ip"></param> /// <param name="ipSection"></param> /// <returns></returns> public static Boolean ipExistsInRange(String ip,String ipSection) { ipSection = ipSection.Trim(); ip = ip.Trim(); int IDx = ipSection.IndexOf('-'); String beginIP = ipSection.Substring(0,IDx); String endIP = ipSection.Substring(IDx + 1); return getIp2long(beginIP) <= getIp2long(ip) && getIp2long(ip) <= getIp2long(endIP); } public static long getIp2long(String ip) { ip = ip.Trim(); String[] ips = ip.Split('.'); long ip2long = 0L; for (int i = 0; i < 4; ++i) { ip2long = ip2long << 8 | Int64.Parse(ips[i]); } return ip2long; } public static long getIp2long2(String ip) { ip = ip.Trim(); String[] ips = ip.Split('.'); long ip1 = Int64.Parse(ips[0]); long ip2 = Int64.Parse(ips[1]); long ip3 = Int64.Parse(ips[2]); long ip4 = Int64.Parse(ips[3]); long ip2long = 1L * ip1 * 256 * 256 * 256 + ip2 * 256 * 256 + ip3 * 256 + ip4; return ip2long; }以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持编程小技巧!
总结以上是内存溢出为你收集整理的C# 获取IP及判断IP是否在区间全部内容,希望文章能够帮你解决C# 获取IP及判断IP是否在区间所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)