Created
May 19, 2012 01:06
-
-
Save bmc/2728451 to your computer and use it in GitHub Desktop.
Quick and dirty Ruby module to determine if IP address (as string) is RFC-1918 address
This file contains 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
module RFC1918 | |
def is_rfc1918_address(ip) | |
unless ip =~ /^(\d{1,3}).(\d{1,3}).(\d{1,3}).(\d{1,3})$/ | |
raise "#{ip} is not an IP address" | |
end | |
octets = [$1, $2, $3, $4].map &:to_i | |
raise "#{ip} is a bad IP address" unless octets.all? {|o| o < 256} | |
# The Internet Assigned Numbers Authority (IANA) has reserved the | |
# following three blocks of the IP address space for private internets: | |
# | |
# 10.0.0.0 - 10.255.255.255 (10/8 prefix) | |
# 172.16.0.0 - 172.31.255.255 (172.16/12 prefix) | |
# 192.168.0.0 - 192.168.255.255 (192.168/16 prefix) | |
(octets[0] == 10) || | |
((octets[0] == 172) && (octets[1] >= 16) && (octets[1] <= 31)) || | |
((octets[0] == 192) && (octets[1] == 168)) | |
end | |
end |
You might want to consider adding
IPAddr.new('fd00::/8')
to your array, unless you work with IPv4 only.
For the holyketzer's solution add require 'ipaddr'
just to save couple minutes of your life.
There's a build-in method private?
for that:
https://ruby-doc.org/stdlib-2.5.1/libdoc/ipaddr/rdoc/IPAddr.html#method-i-private-3F
https://ruby-doc.org/stdlib-2.5.1/libdoc/ipaddr/rdoc/IPAddr.html#method-i-private-3F
Ruby 2.4 hasn't this method yet and Ruby 2.5 was released a couple of month ago since my answer, so now it's simple:
require "ipaddr"
IPAddr.new("192.168.0.1").private? # => true
IPAddr.new("41.42.43.44").private? # => false
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A little bit nicer solution: