IP校验 不能以0、127及224-255开头;是正确的IP 
public class IpReg {
	
	public static void main(String[] args) {
		String s = "225.255.255.255";
		
		boolean b = false;
		//只要捕获到了异常,说明Ip是非法的,根据需要处理异常
		try {
			b = validateIP(s);
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("验证结果为 :"+b);
	}
	
	public static boolean validateIP(String ip){
		boolean b = false;
		String[] ips = ip.split("\\.");
		if(ips.length!=4){
			throw new IllegalArgumentException("Illegal IP ["+ip+"]");
		}
		
		//对第一组进行验证
		String[] ips1 = ips[0].split("");
		if(ips1.length>4){
			throw new IllegalArgumentException("Illegal IP ["+ip+"],String ["+ips[0]+"] given that length must less than 4");
		}
		
		int fip = 0;
		try {
			fip = Integer.parseInt(ips[0]);
		} catch (NumberFormatException e) {
			throw new IllegalArgumentException("Illegal IP ["+ip+"],param ["+ips[0]+"] given must be type of number!");
		}
		//如果没有抛出异常,则全部是数字,进行判断是否合法
		if(fip<0 | fip == 0 | fip == 127){
			throw new IllegalArgumentException("Illegal IP ["+ip+"], can not begin with "+fip);
		}else{
			b = true;
			for(int i=224;i<=255;i++){
				if(fip==i){
					throw new IllegalArgumentException("Illegal IP ["+ip+"], can not begin with "+fip);
				}
			}
		}
		//对剩下的三组进行验证
		boolean b2 = validate(ips[1]);
		boolean b3 = validate(ips[2]);
		boolean b4 = validate(ips[3]);
		
		return b&b2&b3&b4;
	}
	
	private static boolean validate(String subip){
		String[] ips = subip.split("");
		if(ips.length>4){
			throw new IllegalArgumentException("Illegal IP ["+subip+"],String ["+subip+"] given that length must less than 4");
		}
		Integer ip = null;
		
		try {
			ip = Integer.parseInt(subip);
		} catch (NumberFormatException e) {
			throw new IllegalArgumentException("Illegal IP ["+subip+"],param ["+ips[0]+"] given must be type of number!");
		}
		//如果没有抛出异常,则全部是数字,进行判断是否合法
		if(ip<=255 && ip>-1){
			return true;
		}else{
			throw new IllegalArgumentException("Illegal IP ["+subip+"],param ["+subip+"] given that must less than 256 and great than -1");
		}
	}
}
  
  
  
    
      
        
          - IpReg.zip (973 Bytes)
 
          
          - 下载次数: 2