I have an array like this
var ALLOW_SUBNET = ['192.168.1.', '192.168.2.', '192.168.3.' , '192.168.4.'];
And I can get IP address of PC Client by using my own function:
getIPClient()
var ipclient = input.getIPClient();
My question is how can I check if client IP is within my allowed subnet, I tried to use indexOf() function, but result was wrong. For example:
if IP Client is 192.168.1.115 => allow
if IP Client is 192.168.5.115 => deny.
You could use Array#some
for it and check if a part of ALLOW_SUBNET
is inside of ip
at position 0
.
function check(ip) {
return ALLOW_SUBNET.some(function (a) { return !ip.indexOf(a); });
}
var ALLOW_SUBNET = ['192.168.1.', '192.168.2.', '192.168.3.', '192.168.4.'];
console.log(check('192.168.1.115'));
console.log(check('192.168.5.115'));
ES6 with String#startsWith
function check(ip) {
return ALLOW_SUBNET.some(a => ip.startsWith(a));
}
var ALLOW_SUBNET = ['192.168.1.', '192.168.2.', '192.168.3.', '192.168.4.'];
console.log(check('192.168.1.115'));
console.log(check('192.168.5.115'));
Here is a solution.
var ALLOW_SUBNET = ['192.168.1.', '192.168.2.', '192.168.3.', '192.168.4.'];
function checkIP(ip) {
var allow = false;
for (var i = 0; i <= ALLOW_SUBNET.length; i++) {
if (ip.indexOf(ALLOW_SUBNET[i]) > -1) {
allow = true;
break;
}
}
return allow;
}
console.log(checkIP('192.168.9.3'));
console.log(checkIP('192.168.1.3'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With