Skip to content

Instantly share code, notes, and snippets.

@GeoffWilliams
Created January 4, 2017 01:10
Show Gist options
  • Select an option

  • Save GeoffWilliams/01687042a361d2830cb50631d036b3d9 to your computer and use it in GitHub Desktop.

Select an option

Save GeoffWilliams/01687042a361d2830cb50631d036b3d9 to your computer and use it in GitHub Desktop.
Module to detect whether an IP address is rfc1918 or not (private class A, B, C + loopback)
# From https://gist.github.com/bmc/2728451
module RFC1918
def self.is_unroutable(ip)
if ! (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)) ||
(octets[0] == 127)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment