通过纯JavaScript比较IP地址

时间:2013-12-22 15:56:10

标签: javascript

我有一组IP地址。我试图将它与我作为标题的一部分获得的IP地址匹配。如果返回的IP与数组中的任何一个IP匹配,则传递成功消息,否则失败

这是我拥有的,但它不起作用

var redirectIPExcludeList = [213.235.0.105,213.235.0.106,86.12.149.50,79.173.148.50,207.164.206.66]
var returnedIp = 1.0.0.255

for(var i =0; i<=redirectIPExcludeList.length; i++){
    if(returnedIp == redirectIPExcludeList[i]){
        alert('perfect match')
    }else{
        alert('falied')
    }
}

我有点想到,我可能需要拆分这些IP才能比较它们但却无法正确理解

这是我的小提琴

http://jsfiddle.net/sghoush1/MeR9k/

3 个答案:

答案 0 :(得分:2)

将所有IP声明为数组中的字符串和returnsIp(将它们包装到&#34;&#34;)。

var redirectIPExcludeList = ["213.235.0.105","213.235.0.106","86.12.149.50","79.173.148.50","207.164.206.66"];
var returnedIp = "1.0.0.255";

答案 1 :(得分:0)

没有dataType评估IP地址/号码,包含4位小数。因此,将它们设为 string 数据类型,如

var redirectIPExcludeList = ["213.235.0.105","213.235.0.106","86.12.149.50","79.173.148.50","207.164.206.66"]
var returnedIp = "1.0.0.255"

Fiddle

答案 2 :(得分:0)

将它们比作字符串

if("1.0.0.255" == "213.235.0.105" )

立即尝试。

var redirectIPExcludeList = ["213.235.0.105","213.235.0.106","86.12.149.50","79.173.148.50","207.164.206.66","1.0.0.255"]
var returnedIp = "1.0.0.255"

for(var i =0; i< redirectIPExcludeList.length; i++){
    if(returnedIp == redirectIPExcludeList[i]){
        alert('perfect match : '+ redirectIPExcludeList[i] + ' = ' +returnedIp )

    }else{
        alert('falied : '+ redirectIPExcludeList[i] + ' != ' +returnedIp)
    }

}