【发布时间】:2012-01-09 02:48:54
【问题描述】:
我有像 192.168.1.0/24 这样的 CIDR 格式的文件,它被转换成这两列结构
3232236030 3232235777
每个字符串 IP 地址转换都使用以下代码进行:
String subnet = "192.168.1.0/24";
SubnetUtils utils = new SubnetUtils(subnet);
Inet4Address a = (Inet4Address) InetAddress.getByName(utils.getInfo().getHighAddress());
long high = bytesToLong(a.getAddress());
Inet4Address b = (Inet4Address) InetAddress.getByName(utils.getInfo().getLowAddress());
long low = bytesToLong(b.getAddress());
private static long bytesToLong(byte[] address) {
long ipnum = 0;
for (int i = 0; i < 4; ++i) {
long y = address[i];
if (y < 0) {
y += 256;
}
ipnum += y << ((3 - i) * 8);
}
return ipnum;
}
考虑到(low high : 3232236030 3232235777) 有超过 500 万个条目。
还会有相交,因此 IP 可以来自多个范围。仅第一个就可以了。
数据是只读的。
找到ipToBefiltered 所属范围的最快方法是什么?该结构将完全在内存中,因此无需进行数据库查找。
更新:
我发现了这个Peerblock 项目(它的下载量超过百万,所以我认为它必须有一些快速算法): http://code.google.com/p/peerblock/source/browse/trunk/src/pbfilter/filter_wfp.c
有谁知道该项目使用什么技术来创建范围列表而不是搜索它们?
【问题讨论】:
-
"该结构将完全在内存中,因此没有数据库查找。" - 为什么没有内存数据库?
-
find the range the ipToBefiltered belongs to?您想知道给定 IP 的范围,而不仅仅是 T/F 是否在 一些 定义的范围内? -
@Mat 范围内是否有重叠?