C# 获取IP及判断IP是否在区间
程序员文章站
2022-06-07 10:09:37
话不多说,请看代码:
///
/// 获取客户端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; }
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持!
上一篇: 冬季怎么选穿丝袜 参照3标准健康爱美
下一篇: 怎么减肥效果好 推荐女人减肥的最好方法