Class: IpRange

Inherits:
Range show all
Defined in:
lib/gorillib/type/ip_address.rb

Constant Summary collapse

CIDR_RE =
%r{\A(\d+\.\d+\.\d+\.\d+)/([0-3]\d)\z}

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Range

#sum

Constructor Details

#initialize(min_or_range, max = nil, exclusive = false) ⇒ IpRange

Returns a new instance of IpRange.

Raises:



117
118
119
120
121
122
123
124
125
126
127
# File 'lib/gorillib/type/ip_address.rb', line 117

def initialize(min_or_range, max=nil, exclusive=false)
  if max.nil?
    min       = min_or_range.min
    max       = min_or_range.max
    exclusive = min_or_range.exclude_end?
  else
    min       = min_or_range
  end
  raise ArgumentError, "Only inclusive #{self.class.name}s are implemented" if exclusive
  super( IpNumeric.new(min), IpNumeric.new(max), false )
end

Class Method Details

.from_cidr(cidr_str) ⇒ Object



147
148
149
150
151
152
# File 'lib/gorillib/type/ip_address.rb', line 147

def self.from_cidr(cidr_str)
  cidr_str =~ CIDR_RE or raise ArgumentError, "CIDR string should look like an ip address and bitness, eg 1.2.3.4/24 (got #{cidr_str})"
  bitness    = $2.to_i
  ip_address = IpNumeric.from_dotted($1)
  new( ip_address.bitness_min(bitness), ip_address.bitness_max(bitness) )
end

Instance Method Details

#bitness_blocks(bitness) ⇒ Object

Raises:



129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
# File 'lib/gorillib/type/ip_address.rb', line 129

def bitness_blocks(bitness)
  raise ArgumentError, "IP addresses have only 32 bits (got #{bitness.inspect})" unless (0..32).include?(bitness)
  return [] if min.nil?
  lsbs = 32 - bitness
  middle_min = min.bitness_max(bitness) + 1
  return [[min, max]] if max < middle_min
  middle_max = max.bitness_min(bitness)
  blks = []
  stride = 1 << lsbs
  #
  blks << [min, IpNumeric.new(middle_min-1)]
  (middle_min ... middle_max).step(stride){|beg| blks << [IpNumeric.new(beg), IpNumeric.new(beg+stride-1)] }
  blks << [IpNumeric.new(middle_max), max]
  blks
end