Skip to content

Instantly share code, notes, and snippets.

@bmc
Created May 19, 2012 01:06
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bmc/2728451 to your computer and use it in GitHub Desktop.
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
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
@holyketzer
Copy link

A little bit nicer solution:

PRIVATE_IPS = [
  IPAddr.new('10.0.0.0/8'),
  IPAddr.new('172.16.0.0/12'),
  IPAddr.new('192.168.0.0/16'),
].freeze

def private_ip?(ip_address)
  if ip_address.is_a?(String)
    ip_address = IPAddr.new(ip_address)
  end
  
  PRIVATE_IPS.any? { |private_ip| private_ip.include?(ip_address) }
end

@and0x000
Copy link

and0x000 commented Sep 3, 2018

You might want to consider adding
IPAddr.new('fd00::/8')
to your array, unless you work with IPv4 only.

@terencebor
Copy link

terencebor commented May 8, 2020

For the holyketzer's solution add require 'ipaddr' just to save couple minutes of your life.

@nglx
Copy link

nglx commented Jan 17, 2023

@holyketzer
Copy link

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