验证IP地址不是0.0.0.0或多播地址 [英] Validate IP address is not 0.0.0.0 or multicast address
问题描述
使用JavaScript如何验证IP地址x.x.x.x是有效的IPV4单播地址,例如不是0.0.0.0或多播(224.0.0.0到224.0.0.255,224.0.1.0到238.255.255.255,239.0.0.0到239.255.255.255)?
Using JavaScript how would I validate an IP address "x.x.x.x" is a valid IPV4 unicast address e.g. is not 0.0.0.0 or multicast (224.0.0.0 to 224.0.0.255, 224.0.1.0 to 238.255.255.255, 239.0.0.0 to 239.255.255.255)?
推荐答案
首先你需要把它变成一个数字,使用这个函数: -
First you need to get it into a number, use this function:-
function IPToNumber(s)
{
var arr = s.split(".");
var n = 0
for (var i = 0; i < 4; i++)
{
n = n * 256
n += parseInt(arr[i],10)
}
return n;
}
看看你的规格,虽然你似乎列出了一系列范围似乎与我连续,可以简化为(224.0.0.0至239.255.255.255)。因此,你可以测试: -
Looking at you spec, whilst you seem to list a series of ranges those ranges appear to be contiguous to me, that is can be simplified to (224.0.0.0 to 239.255.255.255). Hence you can test with:-
var min = IPToNumber("224.0.0.0");
var max = IPToNumber("239.255.255.255");
var ipNum = IPToNumber(sTestIP);
var isValid = (ipNum != 0 && (ipNum < min || ipNum > max))
当然注意,如果不知道目的地子网,则无法判断该地址是该子网的网络地址还是广播地址。
Note of course that without knowledge of the destinations subnet you can't tell whether the address is the network address or the broadcast address for that subnet.
这篇关于验证IP地址不是0.0.0.0或多播地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!