Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Public And Private IP Detection

DZone's Guide to

Public And Private IP Detection

·
Free Resource
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
Topics:

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}