class IP

Constants

BITS_IN_SEGMENT
EXPECTED_CIDRS

www.cloudflare.com/ips-v4

Attributes

bits[R]

Public Class Methods

expected_cidrs() click to toggle source
# File lib/ip.rb, line 37
def self.expected_cidrs
  @cf_ips ||= EXPECTED_CIDRS.map { |cidr| IP.new(cidr) }
end
new(cidr_str) click to toggle source

accepts plain IP address, or CIDR notation

# File lib/ip.rb, line 13
def initialize(cidr_str)
  @ip, bits = cidr_str.split('/')
  @bits = bits.to_i if bits
end

Public Instance Methods

includes?(ip_addr) click to toggle source

IP.new('192.168.0.1/24').includes?(IP.new('192.168.0.1'))

# File lib/ip.rb, line 31
def includes?(ip_addr)
  len = self.bits
  ip_slice = ->(ip) { ip.to_binary[0,len] }
  ip_slice.(self) == ip_slice.(ip_addr)
end
sketch?() click to toggle source
# File lib/ip.rb, line 26
def sketch?
  @sketch ||= IP.expected_cidrs.none? { |cidr| cidr.includes?(self) }
end
to_binary() click to toggle source

192.168.0.1 -> 11000000101010000000000000000001

# File lib/ip.rb, line 21
def to_binary
  n_to_b = ->(n) { n.to_s(2).rjust(BITS_IN_SEGMENT, '0') }
  @binary_ip ||= @ip.split('.').map { |segment| n_to_b.(segment.to_i) }.join
end
to_s() click to toggle source
# File lib/ip.rb, line 18
def to_s; @ip; end