Skip to content

Instantly share code, notes, and snippets.

@ik5
Created March 6, 2012 11:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ik5/1985691 to your computer and use it in GitHub Desktop.
Save ik5/1985691 to your computer and use it in GitHub Desktop.
function to detect if an IPv4 address should be considered local
def internal_ip?(s)
s =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/
# based on http://www.ietf.org/rfc/rfc3330.txt
return case $1
when '0', '10', '127'
true
when '169'
# link local Zero Conf
(('16'..'31').include? $2) || ($2.eql? '254')
when '172'
('16'..'31').include? $2
when '192'
$2.eql? '168'
when ('224'..'239'), ('240'..'255')
true
else
false
end
end
@ik5
Copy link
Author

ik5 commented Mar 6, 2012

you can test it like so:

ips = ['127.0.0.2', '192.118.0.33', '192.168.3.33', '10.0.3.45',
'0.0.0.0', '169.19.3.1', '172.16.9.1',
'255.255.255.255', '225.2.2.1', '169.254.0.57']

ips.each do |i|
puts "#{i}=#{internal_ip?(i)}"
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment