您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息
免费发信息
三六零分类信息网 > 长治分类信息网,免费分类信息发布

C#获取IP及判断IP是否在区间的示例代码

2024/11/8 17:06:36发布55次查看
本文主要介绍了c# 获取ip及判断ip是否在区间的方法。具有很好的参考价值,下面跟着小编一起来看下吧
话不多说,请看代码:
/// <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是否在区间的示例代码的详细内容。
长治分类信息网,免费分类信息发布

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录