File: ipcidr.rb

package info (click to toggle)
puppet-module-puppetlabs-firewall 8.1.7-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 512 kB
  • sloc: ruby: 2,674; sh: 39; makefile: 2
file content (39 lines) | stat: -rw-r--r-- 919 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# frozen_string_literal: true

require 'puppet_x'
require 'ipaddr'

module PuppetX::Firewall # rubocop:disable Style/ClassAndModuleChildren
  # IPCidr object wrapper for IPAddr
  class IPCidr < IPAddr
    def initialize(ipaddr, family = Socket::AF_UNSPEC)
      super(ipaddr, family)
    rescue ArgumentError => e
      raise ArgumentError, "Invalid address from IPAddr.new: #{ipaddr}" if e.message.include?('invalid address')

      raise e
    end

    def netmask
      _to_string(@mask_addr)
    end

    def prefixlen
      m = case @family
          when Socket::AF_INET
            IN4MASK
          when Socket::AF_INET6
            IN6MASK
          else
            raise 'unsupported address family'
          end
      return Regexp.last_match(1).length if %r{\A(1*)(0*)\z} =~ (@mask_addr & m).to_s(2)

      raise 'bad addr_mask format'
    end

    def cidr
      "#{self}/#{prefixlen}"
    end
  end
end