Create a gist now

Instantly share code, notes, and snippets.

@zyphlar /example.js
Last active Aug 29, 2015

Javascript / JQuery for testing if a given IP is in the IANA reserved range
alert( is_iana_reserved_ip("192.168.5.5") );
alert( is_iana_reserved_ip("192.200.5.5") );
function IPnumber(IPaddress) {
var ip = IPaddress.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);
if(ip) {
return (+ip[1]<<24) + (+ip[2]<<16) + (+ip[3]<<8) + (+ip[4]);
}
// else ... ?
return null;
}
function IPmask(maskSize) {
return -1<<(32-maskSize)
}
function is_iana_reserved_ip(ip){
// "ip": maskbits
// per http://www.iana.org/assignments/ipv4-address-space/ipv4-address-space.xhtml
var reserved = {
"0.0.0.0": 8,
"10.0.0.0": 8,
"100.64.0.0": 10,
"127.0.0.0": 8,
"169.254.0.0": 16,
"172.16.0.0": 12,
"192.0.0.0": 24,
"192.0.2.0": 24,
"192.88.99.0": 24,
"192.168.0.0": 16,
"198.18.0.0": 15,
"198.51.100.0": 24,
"203.0.113.0": 24,
"224.0.0.0": 8,
"225.0.0.0": 8,
"226.0.0.0": 8,
"227.0.0.0": 8,
"228.0.0.0": 8,
"229.0.0.0": 8,
"230.0.0.0": 8,
"231.0.0.0": 8,
"232.0.0.0": 8,
"233.0.0.0": 8,
"234.0.0.0": 8,
"235.0.0.0": 8,
"236.0.0.0": 8,
"237.0.0.0": 8,
"238.0.0.0": 8,
"239.0.0.0": 8,
"255.255.255.255": 32,
};
var results = $.map(reserved, function(m, i){
return (IPnumber(i) & IPmask(m)) == (IPnumber(ip) & IPmask(m));
});
if( results.indexOf(true) > -1){
return true;
}
else {
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment