IPV4地址運算,計算當前IP地址是否在設定範圍內
1.理解ip地址的含義
常用的ip地址是遵循IPv4協議,由32位的二進制數組成,在具體設置時看到的是4個0~255之間的數組成,常見就有本地環回地址“127.0.0.1”,還有常用的局域網地址“192.168.0.1”之類的。所以IPv4的地址能表示的範圍就2的31次冪到2的0次冪之間。
2.如何把常見的10進製表示的ip地址轉換成二進制
要理解10進制數在計算機內存中也是以0或1的方式去表示的,同時移位運算相比其他的四則運算對於計算機來說,運算效率更高。所以只需要定義一個範圍大於或等於2的31次冪的整數類型,來進行位運算即可。在java中,int型只有4個字節,長度不夠,所以選擇使用long型,long型有8個字節,除去符號位足以保存2的31次冪的數。
代碼如下
/**
* 將4位的ip地址數組轉二進制對應的十進制數.
* @param ipArr 4位的ip地址int數組.
* @return ip地址數組轉二進制對應的十進制數.
*/
private static long getIpByteToTen(int[] ipArr){
//定義臨時值
long temp = 0;
//迭代數組
for(int i : ipArr ){
//左移8位後,加上當前數值
temp =(temp << 8) + i;
}
return temp;
}
用int型的數組保存切割好的ip地址,然後迭代整個數組,首個數字進入循環,"<<"(符號位保持不動的左移位運算),左移8位後加上首個數字。繼續迭代,再左移8位在加上當前第二個數字,依次迭代完整個數組。此時內存中保存的temp值就是真實ip地址的數值。
3.具體使用
代碼如下
/**
* IP地址運算判斷是否在分配的地址範圍內.
* @param enterIp 起始ip地址.
* @param endIp 結束ip地址.
* @param nowIp 當前ip地址.
* @return 運算結果 true :當前地址在範圍內 false:當前地址不在範圍內.
* @throws IpAddrFormatException ip地址轉化異常。
*/
public static boolean isSecurityIpAddr(String enterIp,String endIp,String nowIp) throws IpAddrFormatException {
//傳入的ip地址字符串,切成數組
String [] enterIpArry = enterIp.split("\\.");
String [] endIpArry = endIp.split("\\.");
String [] nowIpArry = nowIp.split("\\.");
//初始化接受轉化數字的數組
int [] enterIpNumArry = new int[4];
int [] endIpNumArry = new int[4];
int [] nowIpNumArry = new int[4];
//判斷數組格式是否正確
if(enterIpArry.length==4&&endIpArry.length==4){
try {
//迭代起始ip地址數組,將String轉成int
for(int i=0 ; i < 4; i++){
enterIpNumArry[i] = Integer.parseInt(enterIpArry[i]);
}
//迭代結束ip地址數組,將String轉成int
for(int i=0 ; i < 4; i++){
endIpNumArry[i] = Integer.parseInt(endIpArry[i]);
}
//迭代當前ip地址數組,將String轉成int
for(int i=0 ; i < 4; i++){
nowIpNumArry[i] = Integer.parseInt(nowIpArry[i]);
}
}catch (NumberFormatException ex){
//捕獲數值轉化異常
//拋出自定義異常
throw new IpAddrFormatException( ex.getCause());
}
}else {
//拋出自定義異常
throw new IpAddrFormatException("ipAddr format is not true");
}
//定義long型獲取ip地址的二進制轉十進制數
long enterIpTenNum = getIpByteToTen(enterIpNumArry);
long endIpTenNum = getIpByteToTen(endIpNumArry);
long nowIpTenNum = getIpByteToTen(nowIpNumArry);
//判斷當前ip數值是否在範圍內
if(nowIpTenNum >= enterIpTenNum && nowIpTenNum <= endIpTenNum){
return true;
}
return false;
}
現在已經把實現方法封裝到工具方法中。
測試代碼如下
@Test
public void contextLoads() throws IpAddrFormatException {
boolean isSecurity = IPAddrUtil.isSecurityIpAddr("192.168.0.10","192.168.0.55","192.168.0.20");
}
希望有有緣人可以看到,很簡單,也很好用。