I’m trying to determine if a gateway address in with the same subnet as another IP Address.
The code I’m using is :
var ip2long = function( ip ){
var components;
if ( components = ip.match(/^(d{1,3}).(d{1,3}).(d{1,3}).(d{1,3})$/) ) {
var iplong = 0;
var power = 1;
for ( var i=4; i>=1; i-=1 ) {
iplong += power * parseInt( components[i] );
power *= 256;
}
return iplong;
}
else return -1;
}
var inSubNet = function( ip, subnet ) {
var mask, base_ip, long_ip = ip2long(ip);
if ( ( mask = subnet.match(/^(.*?)/(d{1,2})$/) ) && ( ( base_ip=ip2long( mask[1] ) ) >= 0) ) {
var freedom = Math.pow(2, 32 - parseInt(mask[2]));
return (long_ip > base_ip) && (long_ip < base_ip + freedom - 1);
}
else return false;
}
The values I’m using are:
ipaddress = '192.168.10.20'
gateway = '192.168.250.1'
mask = '16'
running inSubNet( ipaddress, gateway + '/' + mask )
returns false.
If I change the subnet so the third octet is 10 or lower then it works. If it’s 11 or more then it returns false.
If I’ve understood the subnet correctly I would expect any gateway address 192.168.x.x to return true.
Can some one advise how I can do this.
Thanks