[英]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.