簡體   English   中英

如何存儲IP地址范圍與位置

[英]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 (位置)。

間隔樹段樹呢? 如果您的IP地址范圍“集”是動態的,則間隔樹應該更好。 如果范圍是靜態的,則細分樹應該更好,並且據說在執行“刺入查詢”時效果更好。

間隔樹:

在計算機科學中,間隔樹是用於存儲間隔的有序樹數據結構。 具體地說,它允許人們有效地找到與任何給定間隔或點重疊的所有間隔。 它通常用於窗口查詢。

查詢時間O(log n)

段樹:

在計算機科學中,段樹是用於存儲間隔或段的樹數據結構。 它允許查詢哪些存儲段包含給定點。

查詢O(log n + k)中的一個點,k是檢索到的間隔或分段的數量。

實現方式:

Java中的段樹實現

Java中間隔樹的實現

我會使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM