Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
800 views
in Technique[技术] by (71.8m points)

javascript - Validate IP address is not 0.0.0.0 or multicast address

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)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;
}

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...