Skip to content

Instantly share code, notes, and snippets.

@iongion
Created February 13, 2014 14:49
Show Gist options
  • Save iongion/8976282 to your computer and use it in GitHub Desktop.
Save iongion/8976282 to your computer and use it in GitHub Desktop.
Check if IP or hostnames are local, with loose restrictions on host name
function ipv42long(addr) {
var octets = addr.split('.')
return (parseInt(octets[0]) * 16777216) + (parseInt(octets[1]) * 65536) + (parseInt(octets[2]) * 256) + parseInt(octets[3])
}
function isPrivateIP(addr) {
var is_private = false,
ranges = [
['10.0.0.0', '10.255.255.255'],
['172.16.0.0', '172.31.255.255'],
['192.168.0.0', '192.168.255.255'],
['169.254.0.0', '169.254.255.255'],
['127.0.0.0', '127.255.255.255']
],
longip = ipv42long(addr)
if (longip != -1) {
for (var r=0;r<ranges.length;r++) {
var range = ranges[r],
r_s = range[0],
r_e = range[1]
if ((longip >= ipv42long(r_s)) && (longip <= ipv42long(r_e))) {
is_private = true
break
}
}
}
return is_private
}
function isLocalHost(addr) {
var rx = new RegExp('http(|s)://localhost.*')
return rx.test(addr)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment