Class: IPAddr

Inherits:
Object show all
Defined in:
lib/svcbase/ipaddr_helper.rb

Overview

monkey-patch IPAddr class to provide some cidr-related accessors

Constant Summary collapse

PRIVATE_IP_RANGES =
[
  IPAddr.new('10.0.0.0/8'),
  IPAddr.new('172.16.0.0/12'),
  IPAddr.new('192.168.0.0/16'),
  IPAddr.new('fc00::/7')
].freeze

Instance Method Summary collapse

Instance Method Details

#canonicalObject



20
21
22
# File 'lib/svcbase/ipaddr_helper.rb', line 20

def canonical
  to_s + (cidr? ? "/#{mask_bits}" : '')
end

#cidr?Boolean

Returns:

  • (Boolean)

Raises:

  • (AddressFamilyError)


7
8
9
10
11
12
13
14
# File 'lib/svcbase/ipaddr_helper.rb', line 7

def cidr?
  full_mask = case @family
              when Socket::AF_INET then IN4MASK
              when Socket::AF_INET6 then IN6MASK
              end
  raise AddressFamilyError, 'unsupported address family' unless full_mask
  @mask_addr != full_mask
end

#mask_bitsObject



16
17
18
# File 'lib/svcbase/ipaddr_helper.rb', line 16

def mask_bits
  @mask_addr.to_s(2).sub(/0+$/, '').length
end

#private?Boolean

Returns:

  • (Boolean)


31
32
33
# File 'lib/svcbase/ipaddr_helper.rb', line 31

def private?
  @private ||= PRIVATE_IP_RANGES.any? { |rng| rng.include? self }
end