JavaScript IP范围验证是第二个IP大于第一个IP



你好,我是一个javascript noob,正在为IP范围编写验证器。例如1.1.1.1-2.2.2.2是一个有效的范围,但我想确保第一个IP不大于第二个IP。2.2.2.2-1.1.1.1应返回false。解决这个问题的最佳策略是什么?我应该尝试将每个IP字符串转换为整数映射,然后逐一进行比较吗?我应该迭代for循环1-4并比较之前的第一个值吗。然后是第二等

ipRangeValidator: function(value)
{
if (!value)
return true;
var split = value.split('-');
if (!split || split.length > 2 || split.length === 0) {
return 'Input only an IP or single IP Range';
}
var ips = [];
for (var x = 0; x < split.length; ++x) {
var ip = split[x];
if (isValidIpV6Address(ip)) { 
} else if (isValidIpV4Address(ip)) {
} else {
return ip + ' is not a valid IP address';
}
ips.push(ip);
}
if (ips.length > 1) {
if(true) {            //The Line I am struggling with
return 'The first IP is greater than the second IP';
}
}
return true;
}

这样的东西对你有用吗?

const validRange = '1.1.1.1-2.2.2.2',
invalidRange = '2.2.2.2-1.1.1.1',
anotherInvalidRange = '1.1.3.1-1.1.2.1',
invalidIp = '1.1.300.1-1.1.1.1',

isRangeValid = range => {
const [rangeStart, rangeEnd] = range.split('-'),
[s1,s2,s3,s4] = rangeStart.split('.'),
[e1,e2,e3,e4] = rangeEnd.split('.')
return [s1,s2,s3,s4].some(o => o>255 || o<0) || [e1,e2,e3,e4].some(o => o>255 || o<0) ?
'range contains invalid IP' :
s1>e1 || s2>e2 || s3>e3 || s4>e4 ?
'range start is greater than range end' :
'range is valid'
}

console.log(isRangeValid(validRange))
console.log(isRangeValid(invalidRange))
console.log(isRangeValid(anotherInvalidRange))
console.log(isRangeValid(invalidIp))
.as-console-wrapper{min-height:100%;}

这有帮助吗?

const pad = (num) => String("00"+num).slice(-3);
const ipRange = rng => {
let [ip1,ip2] = rng.split("-");
ip1 = ip1.split(".").map(num => pad(num)).join('.')
ip2 = ip2.split(".").map(num => pad(num)).join('.')
return ip1>ip2;
};
console.log(
ipRange("1.1.1.1-2.2.2.2")
)  
console.log(
ipRange("2.2.2.2-1.1.1.1")
)

相关内容

  • 没有找到相关文章

最新更新