Я возвращаю IP, а затем сравниваю его с диапазоном.
Я просто смотрю на IP-адрес США, и если он попадает в диапазон, я показываю посылку. Я получаю IP правильно, но когда я пытаюсь сопоставить его с диапазоном, я получаю синтаксическую ошибку неожиданного диапазона. Как мне это разрешить?
вот как выглядит мой код
$.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
FYI: IP-адрес, возвращенный из json
является string
, а не числом.
Так что вы подходите, не получится. Здесь проверьте мой подход,
1) Разделите ip-адрес на основе .
возвращается $.getJSON
var x = data.ip.split('.'); // returns ["122", "164", "17", "211"]
2) Вместо использования массива usRange
просто делайте это с помощью простых операций сравнения.
3) Вы не можете сравнивать строки с числами, поэтому конвертируйте эти строки в числа, подобные
+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-адреса в целые числа, используя смещение битов, а затем сравнивает целочисленные значения. Я оставил второй ответ как вариант, но я предпочитаю первый.
Ни одна из этих функций не будет проверять ваши IP-адреса!
/**
* Checks if an IP address is within range of 2 other IP addresses
* @param {String} ip IP to validate
* @param {String} lowerBound The lower bound of the range
* @param {String} upperBound The upper bound of the range
* @return {Boolean} True or false
*/
function isWithinRange(ip, lowerBound, upperBound) {
// Put all IPs into one array for iterating and split all into their own
// array of segments
var ips = [ip.split('.'), lowerBound.split('.'), upperBound.split('.')];
// Convert all IPs to ints
for(var i = 0; i < ips.length; i++) {
// Typecast all segments of all ips to ints
for(var j = 0; j < ips[i].length; j++) {
ips[i][j] = parseInt(ips[i][j]);
}
// Bit shift each segment to make it easier to compare
ips[i] =
(ips[i][0] << 24) +
(ips[i][1] << 16) +
(ips[i][2] << 8) +
(ips[i][3]);
}
// Do comparisons
if(ips[0] >= ips[1] && ips[0] <= ips[2]) return true;
return false;
}
/**
* Checks if an IP address is within range of 2 other IP addresses
* @param {String} ip IP to validate
* @param {String} lowerBound The lower bound of the range
* @param {String} upperBound The upper bound of the range
* @return {Boolean} True or false
*/
function isWithinRange(ip, lowerBound, upperBound) {
// Save us some processing time if the IP equals either the lower bound or
// upper bound
if (ip === lowerBound || ip === upperBound) return true;
// Split IPs into arrays for iterations below. Use same variables since
// we won't need them as strings anymore and because someone will complain
// about wasting memory.
ip = ip.split('.');
lowerBound = lowerBound.split('.');
upperBound = upperBound.split('.');
// A nice, classic for loop iterating over each segment in the IP address
for (var i = 0; i < 4; i++) {
// We need those segments to be converted to ints or our comparisons
// will not work!
ip[i] = parseInt(ip[i]);
lowerBound[i] = parseInt(lowerBound[i]);
upperBound[i] = parseInt(upperBound[i]);
// If this is our first iteration, just make sure the first segment
// falls within or equal to the range values
if (i === 0) {
if (ip[i] < lowerBound[i] || ip[i] > upperBound[i]) {
return false;
}
}
// If the last segment was equal to the corresponding lower bound
// segment, make sure that the current segment is greater
if (ip[i - 1] === lowerBound[i - 1]) {
if (ip[i] < lowerBound[i]) return false;
}
// If the last segment was equal to the corresponding upper bound
// segment, make sure that the current segment is less than
if (ip[i - 1] === upperBound[i - 1]) {
if (ip[i] > upperBound[i]) return false;
}
}
return true;
}