about 8 years ago
有時候要增加安全性的話需要做個IP白名單,客戶不會花錢買 這時候就要自己寫啦
public class IPMask {
public enum Action {
SINGLE, RANGE
}
private Action action;//-- 動作
private String ip;//-- 紀錄IP
private int[] setip; //-- 原設定ip網段
private int[] mask; //-- 設定mask
public IPMask(String ipmask){
String[] im = ipmask.split("/");
this.ip = im[0];
if(im.length == 1){
//為單一IP
action = Action.SINGLE;
}else{
//為網段
action = Action.RANGE;
String[] masks = im[1].split("\\.");
for(int i=0;i<4;i++){
if(this.mask==null) this.mask = new int[4];
this.mask[i] = Integer.parseInt(masks[i]);
}
String[] ips = im[0].split("\\.");
for(int i=0;i<ips.length;i++){
if(this.setip==null) this.setip = new int[4];
this.setip[i] = (Integer.parseInt(ips[i]) & this.mask[i]);
}
}
}
public boolean match(String ip){
boolean allow = true;
if(action == Action.SINGLE){
if(!this.ip.equals(ip))
allow = false;
}else{
String[] ips = ip.split("\\.");
for(int i=0;i<4;i++){
//兩個值做AND之後,如不是符合該網段則不在白名單內
if((Integer.parseInt(ips[i])& mask[i])!= setip[i])
allow = false;
}
}
return allow;
}
public static void main(String[] args) {
IPMask ipmask = new IPMask("192.168.1.0/255.255.255.0");
System.out.println(ipmask.match("192.168.1.60"));
System.out.println(ipmask.match("192.168.2.60"));
ipmask = new IPMask("192.168.1.60");
System.out.println(ipmask.match("192.168.1.60"));
System.out.println(ipmask.match("192.168.2.60"));
}
測試結果
true
false
true
false
在管理介面透過此方法驗證值的正確性
String[] ipmask = request.getParameterValues("ipmask");
public static void setIpmask(String[] ipmask) throws IllegalAccessException{
String temp = null;
String[] ipmaskarray = null;
String[] tempIP = null;
String[] tempMASK = null;
ArrayList iplist = new ArrayList();
for(int i=0;ipmask!=null&&i<ipmask.length;i++){
temp = ipmask[i];
if(temp==null || temp.trim().length()==0)
continue;
ipmaskarray = temp.split("/");
if(ipmaskarray.length!=2)throw new IllegalAccessException("IP格式不合法"+"("+temp+")");
tempIP = ipmaskarray[0].split("\\.");
if(tempIP.length!=4)throw new IllegalAccessException("IP格式不合法"+"("+temp+")");
for(int j=0;j<tempIP.length;j++){
try {
Integer.parseInt(tempIP[j]);
} catch (NumberFormatException e) {
throw new IllegalAccessException("IP數值非數字"+"("+temp+")");
}
}
tempMASK = ipmaskarray[1].split("\\.");
if(tempMASK.length!=4)throw new IllegalAccessException("遮罩格式不合法"+"("+temp+")");
for(int j=0;j<tempMASK.length;j++){
try {
Integer.parseInt(tempMASK[j]);
} catch (NumberFormatException e) {
throw new IllegalAccessException("遮罩數值非數字"+"("+temp+")");
}
}
iplist.add(temp);
}
setIptable("ipmask",iplist);
}
在應用中呼叫此方法過濾
public static HashSet<String> ipset;
public static ArrayList<IPMask> masklist;
public static boolean IPFilter(String ip){
if((ipset==null || ipset.size()==0) && (masklist==null || masklist.size()==0)) return false;
if(ipset.contains(ip)) return true;
else{
for(int i=0;i<masklist.size();i++){
IPMask im = (IPMask)masklist.get(i);
if(im.match(ip)) return true;
}
return false;
}
}