DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Felipe has posted 1 posts at DZone. View Full User Profile

Public And Private IP Detection

11.10.2009
| 4892 views |
  • submit to reddit
        Extending IPAddr:

require 'ipaddr'
class IPAddr
  PrivateRanges = [
    IPAddr.new("10.0.0.0/8"),
    IPAddr.new("172.16.0.0/12"),
    IPAddr.new("192.168.0.0/16")
  ]
  
  def private?
    return false unless self.ipv4?
    PrivateRanges.each do |ipr|
      return true if ipr.include?(self)
    end
    return false
  end

  def public?
    !private?
  end
end

TestCase:

require 'ipaddr'

class IpResolutionTest < Test::Unit::TestCase
  def ip(ipaddr)
    IPAddr.new(ipaddr)
  end
  
  def self.should_be_public_ip(ip)
    should "identify #{ip} as being public" do
      ip(ip).should be_public
    end
  end

  def self.should_be_private_ip(ip)
    should "identify #{ip} as being private" do
      ip(ip).should be_private
    end
  end
  
  context "Ip Resolution" do
    should_be_public_ip "9.255.255.255"
    should_be_public_ip "11.0.0.0"

    (0..5).each do |r1|
      (0..5).each do |r2| 
        should_be_private_ip "10.#{r1*50}.#{r2*50}.10"
      end
    end

    should_be_public_ip "172.15.255.255"
    should_be_public_ip "172.32.0.0"

    (16..31).each do |r1|
      (0..5).each do |r2| 
        should_be_private_ip "172.#{r1}.#{r2*50}.10"
      end
    end

    should_be_public_ip "192.167.255.255"
    should_be_public_ip "192.169.0.0"

    (0..5).each do |r1|
      (0..5).each do |r2| 
        should_be_private_ip "192.168.#{r1*50}.#{r2*50}"
      end
    end
  end
end