2012-08-16 225 views
0

我需要檢查IP地址是否駐留在IP範圍內。使用現有IP地址範圍驗證IP地址

例如10-20.3.5.6包含IP作爲

10.3.5.6 11.3.5.6 。 。 。 20.3.5.6

我需要知道以下幾點:

1)1-10.0-255.0.0-255是IP範圍我在DB。我需要檢查IP「10.0.7.8」是否落在上述指定範圍內。

2)考慮另一種情況是10-20.10-20.10-20.10-20我在DB中有。我需要檢查10-20.10.10-30.10-50範圍內的任何IP是否在上述範圍內?

+0

是不同的存儲範圍在數據庫中的選項?如果您將它們字面地存儲爲字符串10-20.3.5.6,您將無法利用數據庫進行檢查。 – nos 2012-08-16 15:24:35

+0

@nos你可以構建一個視圖。不理想,但理論上可行。 – biziclop 2012-08-16 15:33:35

+0

這看起來不像是一個能夠充分利用視圖的東西......一個類 - 也許,但對於它來說,一個全新的視圖/小部件似乎......是一種浪費。 – Shark 2012-08-16 15:39:54

回答

0

讓我們嘗試這樣的事情......

ArrayList<String> IPlist = getIPTable(); //IPTable has entries 
Pair IPranges[4] = new Pair[4](); 

//Pair isa class that holds two things, like numbers; 

//parse your DB entries into the IPranges 
IPranges[0].low = 10; IPranges[0].hi = 20; 
IPranges[1].low = 3; IPranges[1].hi = 3; 
IPranges[2].low = 5; IPranges[2].hi = 5; 
IPranges[3].low = 6; IPranges[3].hi = 6; 

for(String IP : IPlist) 
{ 
     String octet[4]; //read the octets in the String[] octet using substring(); 
     boolean continue = true; 
     for(int i = 0 ; i < 4 && continue; i++) 
      if(Integer.parseInt(octet[i]) >= IPtable[i].low && Integer.parseInt(octet[i]) <= IPtable[i].hi) 
      { 
       //this is good, do stuff here 
      } 
      else 
      continue = false; //the IP failed to pass the filter, no need to process the rest of it 
     //safely add the IP to the lsit of valid IPs. 
     validIP.add(IP); 
} 



private class Pair 
{ 
    public int low, hi; 

    public Pair(int low, int hi) 
    { 
     this.low = low; this.hi = hi; 
    } 
} //feel free to extend this class to do the checking for you.