Created
March 6, 2012 11:02
-
-
Save ik5/1985691 to your computer and use it in GitHub Desktop.
function to detect if an IPv4 address should be considered local
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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