[英]How to store IP Address range vs location
我有一个问题,我的IP地址范围
IP Location
10.1.100.200- 10.1.100.800 x
10.1.101.200- 10.1.101.800 Y
10.1.102.200- 10.1.102.800 Z etc etc
现在给定一个ip,我想找到例如10.1.101.270之类的位置,应该给YI不想要我试图使用最佳算法存储和搜索它们的代码吗? 如何解决这个问题
B+Tree?
使用TreeMap<K, V>
:您可以存储起始范围以映射位置。 TreeMap
使用Red-Black树数据结构对条目进行排序。 其中包括插入和删除的关键查找操作为O(log n)
。 该图提供了两个有用的功能:
higherEntry(K key)
:返回与严格大于给定键的最小key
关联的key-value
映射关系;如果没有这样的键,则返回null
。
lowerEntry(K key)
:返回与最大键严格小于给定键关联的键-值映射关系;如果没有这样的键,则返回null
。
在使用特定ip作为key
搜索时,您可以尝试查找此左侧和右侧条目,其中包含start ip-range
作为键以及它们对应的位置作为值。 将这些ip-范围与搜索key
进行比较,以确定值V
(位置)。
我会使用Sage建议的TreeMap。 假设没有重叠。
public class IPSegment implements Comparable<IPSegement>{
private long start;
private long end;
public IPSegement(String startIp, String endIp){
//convert the ip address to a 32 bit integer.
}
public int compareTo(IPSegement other){
return this.start - other.start; //assume no overlap
}
public int equals(IPSegement other){
// check both start and end
}
public boolean contains(long ip){
//check whether 'ip' is in this range
}
}
public class IPSegmentMap{
private TreeMap<IPSegement> map = new TreeMap<IPSegement>();
public void add(String start, String end, String location){
//...
}
public String find(String ipAddress){
long ip = convertIPtoInt(ipAddress);
IPSegement request = new IPSegement(ip,ip);
IPSegement exist = map.floorKey(request);
if(exist.contains(ip)){
return map.get(exist);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.