将IP与数组中存储的范围匹配 [英] Match IP with a range stored in an array

查看:95
本文介绍了将IP与数组中存储的范围匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要返回IP,然后在一定范围内进行比较.

I am returning an IP and then comparing it from a range.

我只是在查看美国IP,如果它在范围内,我会显示一个消息.我正确地获取了IP,但是当我尝试将其与范围匹配时,却遇到了意外范围的语法错误.我该如何解决?

I am just looking at the US IP and if it falls in a range I am displaying a messge. I am getting the IP correctly but when I am trying to match it with the range I am getting a syntax error of unexpected range. How should I resolve this?

这是我的代码的样子

$.getJSON("http://jsonip.com", function (data) {
    var x = data.ip;
    $('body').html(x);

    var usRange = [3.0.0.0, 222.229.21.255];
    if (x >= usRange[0] && x <= usRange[1]) {
        alert('US');
    } else alert('outside US');
});

这是我的 小提琴

推荐答案

错误是什么意思,您不能用4个小数点分配数字.

var usRange = [3.0.0.0, 222.229.21.255]; //Not possible

仅供参考::json返回的IP地址是 string ,而不是数字.

FYI: The IP address returned from the json is string, not a number.

所以您的方法行不通.在这里检查我的方法,

So you approach won't work. Here check my approach,

1)根据$.getJSON

var x = data.ip.split('.');  // returns ["122", "164", "17", "211"]

2)只需使用简单的比较操作进行操作即可,而不是使用usRange数组.

2) Instead of using usRange array just do it with simple comparison operations.

3)您无法将字符串与数字进行比较,因此请将这些字符串转换为数字,例如

3) You cannot compare strings with numbers, so convert those strings to numbers like

+x[0] //convert "122" to 122

最后,

$.getJSON("http://jsonip.com", function (data) {
    var x = data.ip.split('.');
    if (+x[0] >= 3 && +x[0] <= 222) {
        if (+x[1] >= 0 && +x[1] <= 229) {
            if (+x[2] >= 0 && +x[2] <= 21) {
                if (+x[3] >= 0 && +x[3] <= 255) {
                    alert("Within range");
                }
            }
        }
    } else {
        alert("Is not within range");
    }
});

这篇关于将IP与数组中存储的范围匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆