IP地址合法性检查

来源:互联网 发布:php 生成器 编辑:程序博客网 时间:2024/04/28 22:09
private static String IPComp = "0123456789.";

public void CheckIP(String IP){
   int i;
   int index;
   String cur;
//判断是否存在非IP字符
   for (i = 0;i < IP.length();i++){
    if (IPComp.indexOf(IP.charAt(i)) == -1){
     throw new yourException(yourErrorString);
    }   
   }
//变换IP为'xxx.'重复的格式
   IP = IP + ".";
//分别获得前四个'xxx.'检查
   for (i = 1;i <= 4;i++){
//判断底i个'xxx.'是否存在(i<=4)
    index = IP.indexOf('.');
    if (index == -1){
     throw new yourException(yourErrorString);
    }
    else{
//获得数字,检查数字范围
     cur = IP.substring(0,index);
     IP = IP.substring(index + 1);
     if (cur.length() > 0 && cur.length() <= 3){
      //change cur to int
      int num = 0;
      for (index = 0;index < cur.length();index++){
       num = num * 10 + (int)cur.charAt(index) - 48;      
      }
      if (num > 255){
       throw new yourException(yourErrorString);
      }
     }
     else{
      throw new yourException(yourErrorString);
     }
    }
   }
//检查是否有多的'xxx.'
   if (IP.indexOf('.') != -1){
    throw new yourException(yourErrorString);
   }
  }
原创粉丝点击