组播ip地址校验问题?

如题,我想使用JavaScript校验组播ip地址,地址范围是224.0.1.0 - 239.255.255.255,请问正则表达式要怎么编写?

阅读 2.2k
5 个回答
export function multicastIp (ip: string) {
  const pattern = /^(224\.0(\.([1-9]|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5]))(\.(\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])))$|^(224)(\.([1-9]|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5]))(\.(\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])){2}$|^(22[5-9]|23[0-9])(\.(\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])){3}$/
  return pattern.test(ip)
}

分别匹配224.0.1-255.x 224.1-255.x.x 225-239.x.x,其中x的取值为0-255

function isValidMulticastIP(ip) {
  const ipPattern = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
  const match = ip.match(ipPattern);
  if (!match) {
    return false;
  }

  const parts = match.slice(1).map(Number);

  if (parts.some(part => part < 0 || part > 255)) {
    return false;
  }

  if (parts[0] === 224 && parts[1] === 0 && parts[2] === 0 && parts[3] === 0) {
    return false;
  }

  return parts[0] >= 224 && parts[0] <= 239;
}
function checkIp(ip) {
    const start = '224.0.1.0'
    const end = '239.255.255.255'
    const ipSum = ip => +ip.split('.').map(n => n.padStart(3,'0')).join('')
    const n = ipSum(ip)
    return n >= ipSum(start) && n <= ipSum(end)
}

对于传入的ip假设其是正确的,如果ip有可能格式不对(比如超过255,或者少传之类的)自己再加一层校验,这里只提供比较的逻辑,对ip的数值部分填满三个字符,然后拼接起来成一个数值来进行比较

新手上路,请多包涵

image.png

const multicastIPRegex = /^(22[4-9]|23[0-9])\.([01]?[0-9]{1,2}|2[0-4][0-9]|25[0-5])\.([01]?[0-9]{1,2}|2[0-4][0-9]|25[0-5])\.([01]?[0-9]{1,2}|2[0-4][0-9]|25[0-5])$/;

// 示例用法
const ipAddress = '225.10.20.30';
if (multicastIPRegex.test(ipAddress)) {
  console.log('有效的组播IP地址');
} else {
  console.log('无效的组播IP地址');
}

补充另外一条正则
^2((3\d|2[5-9])(\.(1\d{0,2}|2([0-4]\d|5[0-5])|[2-9]\d?|0)){3}|24\.((1\d{0,2}|2([0-4]\d|5[0-5])|[2-9]\d?)(\.(1\d{0,2}|2([0-4]\d|5[0-5])|[2-9]\d?|0)){2}|0\.(1\d{0,2}|2([0-4]\d|5[0-5])|[2-9]\d?)(\.(1\d{0,2}|2([0-4]\d|5[0-5])|[2-9]\d?|0))))$
PS,其中的数值区间我有个网页工具可以生成:https://www.regex.top

推荐问题
logo
Microsoft
子站问答
访问
宣传栏