特殊规则IP验证

[b]IP校验 不能以0、127及224-255开头;是正确的IP
[/b]

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");
}
}
}


由于对正则表达式不熟悉,以及时间原因,所以上面这是比较笨的方法,解决问题还是得自己细心,用心,精心,好多问题真的是只要自己稍微花点时间用下心,用点时间,用点力就可以解决得了!下面是正则表达式:
String str_pattern = "^(((?!127)([1-9]|[1-9]\\d|1\\d\\d|2[0-1]\\d|22[0-3]))\\.)(([0-9]|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])\\.){2}([0-9]|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])$";
Pattern pattern = Pattern.compile(str_pattern);
String ip ="127.127.127.245";
Matcher m = pattern.matcher(ip);
boolean b = m.find();
if(b){
System.out.println(m.group());
}else{
System.out.println(b);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值