IP和CIDR校验

IP地址的校验方式通过正则表达式

ip = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\/([0-9]|1\d|2\d|3[0-2])$/;

CIDR的校验

在添加路由策略时,需要主机位全部为0, 通过子网掩码校验方式如下
javascript

checkDestination(value, index) {
    const cidr = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\/([0-9]|1\d|2\d|3[0-2])$/;
    if (!cidr.test(value)) {
      this.error[index].destinationErrorMsg = '请输入正确的cidr格式';
      // this.cidrError = '请输入正确的cidr格式';
      return true;
    }
    if (value === '0.0.0.0/0') {
      this.error[index].destinationErrorMsg = '暂不支持此路由配置';
      // this.cidrError = '暂不支持此路由配置';
      return true;
    }
    return this.maskMatch(value, index);
  }

maskMatch(value, index): boolean {
    let subnet, mask = [], ipInt = [], ipStr, ipSupple;
    subnet = value.split('/')[0]; // '/'before
    mask = value.split('/')[1]; // '/'after
    ipInt = subnet.split('.'); // split ipv4 by .
    ipStr = ''; // all data change to binary system
    ipSupple = '00000000'; // for supple all 8 bit
    for (let i = 0; i < ipInt.length; i++) {
      ipInt[i] = parseInt(ipInt[i]).toString(2); //转换为二进制
      if (ipInt[i].length < 8) {
        let ipLack = ipSupple.slice(0, 8 - ipInt[i].length); //二进制前面位置补0
        ipInt[i] = ipLack + ipInt[i];
      }
      ipStr = ipStr + ipInt[i];
    }
    let localLast = ipStr.lastIndexOf('1') + 1; //获取ip地址中最后一个1所在位置
    if (mask < localLast) {
      this.error[index].destinationErrorMsg = '网段IP地址与掩码不匹配';
      // this.cidrError = '网段IP地址与掩码不匹配';
      return true;
    }
    else {
      return false;
    }
  }

posted @ 2022-07-27 11:13  明月,  阅读(966)  评论(0编辑  收藏  举报