Class: NetAddr::CIDR
- Inherits:
-
Object
- Object
- NetAddr::CIDR
- Defined in:
- lib/cidr.rb
Overview
CIDR - Classless Inter-Domain Routing
A class & series of methods for creating and manipulating CIDR network addresses. Both IPv4 and IPv6 are supported.
This class accepts a CIDR address, via the CIDR.create method, in (x.x.x.x/yy or xxxx::/yy) format for IPv4 and IPv6, or (x.x.x.x/y.y.y.y) for IPv4. CIDR.create then creates either a CIDRv4 or CIDRv6 object. An optional tag hash may be provided with each CIDR as a way of adding custom labels.
Upon initialization, the IP version is auto-detected and assigned to the CIDR. The original IP/Netmask passed within the CIDR is stored and then used to determine the confines of the CIDR block. Various properties of the CIDR block are accessible via several different methods. There are also methods for modifying the CIDR or creating new derivative CIDR’s.
An example CIDR object is as follows:
NetAddr::CIDR.create('192.168.1.20/24')
This would create a CIDR object (192.168.1.0/24) with the following properties:
version = 4
base network = 192.168.1.0
ip address = 192.168.1.20
netmask = /24 (255.255.255.0)
size = 256 IP addresses
broadcast = 192.168.1.255
You can see how the CIDR object is based around the entire IP space defined by the provided IP/Netmask pair, and not necessarily the individual IP address itself.
Instance Attribute Summary collapse
-
#address_len ⇒ Object
readonly
Integer representing number of bits in this CIDR address.
-
#all_f ⇒ Object
readonly
Integer of either 32 or 128 bits in length, with all bits set to 1.
-
#tag ⇒ Object
Hash of custom tags.
-
#version ⇒ Object
readonly
IP version 4 or 6.
Class Method Summary collapse
-
.create(addr, options = nil) ⇒ Object
Synopsis Create a new CIDRv4 or CIDRv6 object.
Instance Method Summary collapse
-
#<(cidr) ⇒ Object
Synopsis Compare the sort order of the current CIDR with a provided CIDR and return true if current CIDR is less than provided CIDR.
-
#<=>(cidr) ⇒ Object
Synopsis Compare the sort order of the current CIDR with a provided CIDR and return: * 1 if the current CIDR is greater than the provided CIDR * 0 if the current CIDR and the provided CIDR are equal (base address and netmask are equal) * -1 if the current CIDR is less than the provided CIDR.
-
#==(cidr) ⇒ Object
(also: #eql?)
Synopsis Compare the sort order of the current CIDR with a provided CIDR and return true if current CIDR is equal to the provided CIDR.
-
#>(cidr) ⇒ Object
Synopsis Compare the sort order of the current CIDR with a provided CIDR and return true if current CIDR is greater than provided CIDR.
-
#[](index) ⇒ Object
Synopsis Provide the IP at the given index of the CIDR.
-
#allocate_rfc3531(netmask, options = nil) ⇒ Object
Synopsis RFC 3531 describes a flexible method for IP subnet allocation from a larger parent network.
-
#arpa ⇒ Object
Synopsis Depending on the IP version of the current CIDR, return either an in-addr.arpa.
-
#bits ⇒ Object
Synopsis Provide number of bits in Netmask.
-
#cmp(cidr) ⇒ Object
Synopsis Compare the current CIDR with a provided CIDR and return: * 1 if the current CIDR contains (is supernet of) the provided CIDR * 0 if the current CIDR and the provided CIDR are equal (base address and netmask are equal) * -1 if the current CIDR is contained by (is subnet of) the provided CIDR * nil if the two CIDR addresses are unrelated.
-
#contains?(cidr) ⇒ Boolean
Synopsis Determines if this CIDR contains (is supernet of) the provided CIDR address or NetAddr::CIDR object.
-
#desc(options = nil) ⇒ Object
Synopsis See to_s.
-
#enumerate(options = nil) ⇒ Object
Synopsis Provide all IP addresses contained within the IP space of this CIDR.
-
#fill_in(list, options = nil) ⇒ Object
Synopsis Given a list of subnets of the current CIDR, return a new list with any holes (missing subnets) filled in.
-
#initialize(ip, netmask = nil, tag = {}, wildcard_mask = nil, wildcard_mask_bit_flipped = false) ⇒ CIDR
constructor
This method performs absolutely no error checking, and is meant to be used only by other internal methods for the sake of the speedier creation of CIDR objects.
-
#ip(options = nil) ⇒ Object
Synopsis Provide original IP address passed during initialization.
-
#is_contained?(cidr) ⇒ Boolean
Synopsis Determines if this CIDR is contained within (is subnet of) the provided CIDR address or NetAddr::CIDR object.
-
#last(options = nil) ⇒ Object
Synopsis Provide last IP address in this CIDR object.
-
#matches?(ip) ⇒ Boolean
Synopsis Given an IP address (or if a NetAddr::CIDR object, then the original IP of that object), determine if it falls within the range of addresses resulting from the combination of the IP and Wildcard Mask of this CIDR.
-
#multicast_mac(options = nil) ⇒ Object
Synopsis Assuming this CIDR is a valid multicast address (224.0.0.0/4 for IPv4 and ff00::/8 for IPv6), return its ethernet MAC address (EUI-48) mapping.
-
#netmask ⇒ Object
Synopsis Provide netmask in CIDR format (/yy).
-
#network(options = nil) ⇒ Object
(also: #base, #first)
Synopsis Provide base network address.
-
#next_ip(options = nil) ⇒ Object
Synopsis Provide the next IP following the last available IP within this CIDR object.
-
#next_subnet(options = nil) ⇒ Object
Synopsis Provide the next subnet following this CIDR object.
-
#nth(index, options = nil) ⇒ Object
Synopsis Provide the nth IP within this object.
-
#range(lower, upper = nil, options = nil) ⇒ Object
Synopsis Given a set of index numbers for this CIDR, return all IP addresses within the CIDR that are between them (inclusive).
-
#remainder(addr, options = nil) ⇒ Object
Synopsis Given a single subnet of the current CIDR, provide the remainder of the subnets.
-
#resize(bits) ⇒ Object
Synopsis Resize the CIDR by changing the size of the Netmask.
-
#resize!(bits) ⇒ Object
Synopsis Resize the current CIDR by changing the size of the Netmask.
-
#set_wildcard_mask(mask, bit_flipped = false) ⇒ Object
Synopsis Set the wildcard mask.
-
#size ⇒ Object
Synopsis Provide number of IP addresses within this CIDR.
-
#subnet(options = nil) ⇒ Object
Synopsis Create subnets for this CIDR.
-
#succ ⇒ Object
Synopsis Provide the next subnet following this CIDR object.
-
#to_i(attribute = :network) ⇒ Object
Synopsis Convert the requested attribute of the CIDR to an Integer.
-
#to_s(options = nil) ⇒ Object
Synopsis Returns network/netmask in CIDR format.
-
#wildcard_mask(bit_flipped = false) ⇒ Object
Synopsis Return the wildcard mask.
Constructor Details
#initialize(ip, netmask = nil, tag = {}, wildcard_mask = nil, wildcard_mask_bit_flipped = false) ⇒ CIDR
This method performs absolutely no error checking, and is meant to be used only by other internal methods for the sake of the speedier creation of CIDR objects. Please consider using #create unless you know what you are doing with 100% certainty.
Arguments:
-
ip - Integer representing an ip address
-
netmask - Integer representing a binary netmask
-
tag - Hash used to append custom tags to CIDR
-
wildcard_mask - Integer representing a binary mask
-
wildcard_mask_bit_flipped - indicates whether or not the wildcard_mask is bit-flipped or not
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 |
# File 'lib/cidr.rb', line 216 def initialize(ip, netmask=nil, tag={}, wildcard_mask=nil, wildcard_mask_bit_flipped=false) @ip = ip if ( self.kind_of?(NetAddr::CIDRv4) ) @version = 4 @address_len = 32 else @version = 6 @address_len = 128 end @all_f = 2**@address_len - 1 if (netmask) @netmask = netmask else @netmask = 2**@address_len - 1 end @network = (@ip & @netmask) @hostmask = @netmask ^ @all_f @tag = tag if (!wildcard_mask) @wildcard_mask = @netmask else @wildcard_mask = wildcard_mask @wildcard_mask = ~@wildcard_mask if (wildcard_mask_bit_flipped) end end |
Instance Attribute Details
#address_len ⇒ Object (readonly)
Integer representing number of bits in this CIDR address
49 50 51 |
# File 'lib/cidr.rb', line 49 def address_len @address_len end |
#all_f ⇒ Object (readonly)
Integer of either 32 or 128 bits in length, with all bits set to 1
46 47 48 |
# File 'lib/cidr.rb', line 46 def all_f @all_f end |
#tag ⇒ Object
Hash of custom tags. Should be in the format tag => value.
43 44 45 |
# File 'lib/cidr.rb', line 43 def tag @tag end |
#version ⇒ Object (readonly)
IP version 4 or 6.
40 41 42 |
# File 'lib/cidr.rb', line 40 def version @version end |
Class Method Details
.create(addr, options = nil) ⇒ Object
Synopsis
Create a new CIDRv4 or CIDRv6 object. CIDR formatted netmasks take precedence over extended formatted ones. CIDR address defaults to a host network (/32 or /128) if netmask not provided. :Mask takes precedence over netmask given within CIDR addresses. Version will be auto-detected if not specified.
NetAddr::CIDR.create('192.168.1.1/24')
NetAddr::CIDR.create('192.168.1.1 255.255.255.0')
NetAddr::CIDR.create(0x0a010001,:Mask => 0xffffff00:Version => 4)
NetAddr::CIDR.create('192.168.1.1',:WildcardMask => ['0.7.0.255', true])
NetAddr::CIDR.create('192.168.1.1',:WildcardMask => [0x000007ff, true]
NetAddr::CIDR.create('192.168.5.0',:WildcardMask => ['255.248.255.0'])
NetAddr::CIDR.create('fec0::/64')
NetAddr::CIDR.create('fec0::/64',:Tag => {'interface' => 'g0/1'})
NetAddr::CIDR.create('::ffff:192.168.1.1/96')
Arguments:
-
addr = CIDR address as a String, or an IP address as an Integer
-
options = Hash with the following keys:
:Mask -- Integer representing a binary IP Netmask :Version -- IP version - Integer :Tag -- Custom descriptor tag - Hash, tag => value. :WildcardMask -- 2 element Array. First element contains a special bit mask used for advanced IP pattern matching. The second element should be set to True if this bit mask is bit flipped.
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 |
# File 'lib/cidr.rb', line 91 def CIDR.create(addr, =nil) known_args = [:Mask, :Version, :Tag, :WildcardMask] ip, netmask, tag = nil, nil, {} version, wildcard_mask ,wildcard_mask_bit_flipped = nil, nil, false netmask_int, all_f = nil, nil # validate options if () raise ArgumentError, "Hash expected for argument 'options' but " + "#{options.class} provided." if (!.kind_of?(Hash) ) NetAddr.validate_args(.keys,known_args) if (.has_key?(:Mask)) netmask_int = [:Mask] raise ArgumentError, "Expected Integer, but #{netmask_int.class} " + "provided for option :Mask." if (!netmask_int.kind_of?(Integer)) end if (.has_key?(:Tag)) tag = [:Tag] if (!tag.kind_of? Hash) raise ArgumentError, "Expected Hash, but #{tag.class} provided for option :Tag." end end if (.has_key?(:Version)) version = [:Version] if (version != 4 && version != 6) raise VersionError, ":Version should be 4 or 6, but was '#{version}'." end end if (.has_key?(:WildcardMask)) if (![:WildcardMask].kind_of?(Array)) raise ArgumentError, "Expected Array, but #{options[:WildcardMask].class} provided for option :WildcardMask." end wildcard_mask = [:WildcardMask][0] if (!wildcard_mask.kind_of?(String) && !wildcard_mask.kind_of?(Integer)) raise ArgumentError, "Expected String or Integer, but #{wildcard_mask.class} provided for wildcard mask." end wildcard_mask_bit_flipped = true if ([:WildcardMask][1] && [:WildcardMask][1].kind_of?(TrueClass)) end end # validate addr arg & set version if not provided by user if (addr.kind_of?(String)) version = NetAddr.detect_ip_version(addr) if (!version) # if extended netmask provided. should only apply to ipv4 if (version == 4 && addr =~ /.+\s+.+/ ) addr,netmask = addr.split(' ') end # if netmask part of ip, then separate ip & mask. if (addr =~ /\//) ip,netmask = addr.split(/\//) if (!ip || !netmask) raise ArgumentError, "CIDR address is improperly formatted. Missing netmask after '/' character." end else ip = addr end NetAddr.validate_ip_str(ip,version) ip = NetAddr.ip_str_to_int(ip,version) elsif (addr.kind_of?(Integer)) ip = addr if (!version) if (ip < 2**32) version = 4 else version = 6 end end NetAddr.validate_ip_int(ip,version) else raise ArgumentError, "String or Integer expected for argument 'addr' but #{addr.class} provided." end # set all_f based on version all_f = 2**32-1 all_f = 2**128-1 if (version == 6) # set netmask. netmask_int takes precedence. set to all_f if no netmask provided if (netmask_int) NetAddr.validate_netmask_int(netmask_int,version,true) netmask = netmask_int elsif (netmask) NetAddr.validate_netmask_str(netmask,version) netmask = NetAddr.netmask_str_to_int(netmask, version) else netmask = all_f end # set wildcard mask if not provided, or validate if provided. if (wildcard_mask) begin if (wildcard_mask.kind_of?(String)) NetAddr.validate_ip_str(wildcard_mask,version) wildcard_mask = NetAddr.ip_str_to_int(wildcard_mask, version) else (wildcard_mask.kind_of?(Integer)) NetAddr.validate_ip_int(wildcard_mask,version) end rescue Exception => error raise ValidationError, "Provided wildcard mask failed validation: #{error}" end end return( NetAddr.cidr_build(version, ip, netmask, tag, wildcard_mask, wildcard_mask_bit_flipped) ) end |
Instance Method Details
#<(cidr) ⇒ Object
Synopsis
Compare the sort order of the current CIDR with a provided CIDR and return true if current CIDR is less than provided CIDR.
Example: cidr = NetAddr::CIDR.create(‘192.168.1.0/24’) cidr < ‘192.168.2.0/24’ => true
Arguments:
-
CIDR address or NetAddr::CIDR object
Returns:
-
true or false
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 |
# File 'lib/cidr.rb', line 261 def <(cidr) if (!cidr.kind_of?(NetAddr::CIDR)) begin cidr = NetAddr::CIDR.create(cidr) rescue Exception => error raise ArgumentError, "Provided argument raised the following " + "errors: #{error}" end end if (cidr.version != @version) raise VersionError, "Attempted to compare a version #{cidr.version} CIDR " + "with a version #{@version} CIDR." end # compare lt = false lt = true if ( NetAddr.cidr_gt_lt(self,cidr) == -1) return(lt) end |
#<=>(cidr) ⇒ Object
Synopsis
Compare the sort order of the current CIDR with a provided CIDR and return:
-
1 if the current CIDR is greater than the provided CIDR
-
0 if the current CIDR and the provided CIDR are equal (base address and netmask are equal)
-
-1 if the current CIDR is less than the provided CIDR
Example: cidr = NetAddr::CIDR.create(‘192.168.1.0/24’) cidr <=> ‘192.168.2.0/24’ => -1 cidr <=> ‘192.168.0.0/24’ => 1 cidr <=> ‘192.168.1.0/24’ => 0
Arguments:
-
CIDR address or NetAddr::CIDR object
Returns:
-
Integer
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 |
# File 'lib/cidr.rb', line 301 def <=>(cidr) if (!cidr.kind_of?(NetAddr::CIDR)) begin cidr = NetAddr::CIDR.create(cidr) rescue Exception => error raise ArgumentError, "Provided argument raised the following " + "errors: #{error}" end end if (cidr.version != @version) raise VersionError, "Attempted to compare a version #{cidr.version} CIDR " + "with a version #{@version} CIDR." end # compare comparasin = NetAddr.cidr_gt_lt(self,cidr) return(comparasin) end |
#==(cidr) ⇒ Object Also known as: eql?
Synopsis
Compare the sort order of the current CIDR with a provided CIDR and return true if current CIDR is equal to the provided CIDR.
Example: cidr = NetAddr::CIDR.create(‘192.168.1.0/24’) cidr == ‘192.168.1.0/24’ => true
Arguments:
-
CIDR address or NetAddr::CIDR object
Returns:
-
true or false
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 |
# File 'lib/cidr.rb', line 336 def ==(cidr) if (!cidr.kind_of?(NetAddr::CIDR)) begin cidr = NetAddr::CIDR.create(cidr) rescue Exception => error raise ArgumentError, "Provided argument raised the following " + "errors: #{error}" end end if (cidr.version != @version) raise VersionError, "Attempted to compare a version #{cidr.version} CIDR " + "with a version #{@version} CIDR." end # compare eq = false eq = true if ( NetAddr.cidr_gt_lt(self,cidr) == 0) return(eq) end |
#>(cidr) ⇒ Object
Synopsis
Compare the sort order of the current CIDR with a provided CIDR and return true if current CIDR is greater than provided CIDR.
Example: cidr = NetAddr::CIDR.create(‘192.168.1.0/24’) cidr > ‘192.168.0.0/24’ => true
Arguments:
-
CIDR address or NetAddr::CIDR object
Returns:
-
true or false
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 |
# File 'lib/cidr.rb', line 373 def >(cidr) if (!cidr.kind_of?(NetAddr::CIDR)) begin cidr = NetAddr::CIDR.create(cidr) rescue Exception => error raise ArgumentError, "Provided argument raised the following " + "errors: #{error}" end end if (cidr.version != @version) raise VersionError, "Attempted to compare a version #{cidr.version} CIDR " + "with a version #{@version} CIDR." end # compare gt = false gt = true if ( NetAddr.cidr_gt_lt(self,cidr) == 1) return(gt) end |
#[](index) ⇒ Object
Synopsis
Provide the IP at the given index of the CIDR.
Example: cidr4 = NetAddr::CIDR.create(‘192.168.1.0/24’) cidr4 => 192.168.1.1/32
Arguments:
-
index = Index number as an Integer
Returns:
-
NetAddr::CIDR object.
408 409 410 411 412 413 414 415 416 417 418 419 420 421 |
# File 'lib/cidr.rb', line 408 def [](index) raise ArgumentError, "Integer expected for argument 'index' but " + "#{index.class} provided." if (!index.kind_of?(Integer) ) addr = @network + index if ( (@hostmask | addr) == (@hostmask | @network) ) addr = NetAddr.cidr_build(@version, addr) else raise BoundaryError, "Index of #{index} returns IP that is out of " + "bounds of CIDR network." end return(addr) end |
#allocate_rfc3531(netmask, options = nil) ⇒ Object
Synopsis
RFC 3531 describes a flexible method for IP subnet allocation from a larger parent network. Given the new netmask for subnet allocations from this CIDR, provide a list of those subnets arranged by the order in which they should be allocated.
Example: cidr = NetAddr::CIDR.create(‘192.168.0.0/16’) cidr.allocate_rfc3531(21, :Strategy => :centermost) => [“192.168.0.0/21”… “192.168.248.0/21”]
Arguments:
-
netmask (in bits) for all new subnet allocations
-
options = Hash with the following keys:
:Objectify -- if true, return NetAddr::CIDR objects :Short -- if true, return IPv6 addresses in short-hand notation :Strategy -- allocation strategy to use. must be either :centermost or :leftmost (default)
Returns:
-
Array of Strings or CIDR objects
442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 |
# File 'lib/cidr.rb', line 442 def allocate_rfc3531(netmask, =nil) short = false objectify = false strategy = :leftmost # validate args raise ArgumentError, "Expected Integer for argument (netmask), but #{max.class} received." if ( !netmask.kind_of?(Integer) ) raise BoundaryError, "Netmask (#{netmask}) is invalid for a version #{self.version} address." if (netmask > @address_len) raise BoundaryError, "Netmask (#{netmask}) cannot be less than #{self.bits}." if (netmask < self.bits) known_args = [:Objectify, :Short, :Strategy] if () if (!.kind_of? Hash) raise ArgumentError, "Expected Hash, but #{options.class} provided." end NetAddr.validate_args(.keys,known_args) if( .has_key?(:Objectify) && [:Objectify] == true ) objectify = true end if( .has_key?(:Short) && [:Short] == true ) short = true end if( .has_key?(:Strategy)) strategy = [:Strategy] raise ArgumentError, "Argument :Strategy must be either :leftmost or :centermost." if (strategy != :leftmost && strategy != :centermost) end end subnet_bits = netmask - self.bits net_lshift = @address_len - netmask new_mask = NetAddr.bits_to_mask(netmask,self.version) cidr_list = [] if (strategy == :leftmost) (0..(2**subnet_bits)-1).each do |num| mirror = NetAddr.binary_mirror(num, subnet_bits) if (!objectify) my_ip_s = NetAddr.ip_int_to_str(@network | (mirror << net_lshift), @version) my_ip_s = NetAddr.shorten(my_ip_s) if (short && @version == 6) cidr_list.push( my_ip_s << '/' << netmask.to_s ) else cidr_list.push( NetAddr.cidr_build(@version, @network | (mirror << net_lshift), new_mask ) ) end end else # :centermost round = 1 bit_count = 1 lshift = subnet_bits/2 lshift -= 1 if (subnet_bits & 1 == 0) # if subnet_bits is even number unique = {} until (bit_count > subnet_bits) (0..2**bit_count-1).each do |num| shifted = num << lshift if ( !unique.has_key?(shifted) ) if (!objectify) my_ip_s = NetAddr.ip_int_to_str(@network | (shifted << net_lshift), @version) my_ip_s = NetAddr.shorten(my_ip_s) if (short && @version == 6) cidr_list.push( my_ip_s << '/' << netmask.to_s ) else cidr_list.push( NetAddr.cidr_build(@version, @network | (shifted << net_lshift), new_mask ) ) end unique[shifted] = true end end lshift -= 1 if (round & 1 == 0) # if even round round += 1 bit_count += 1 end end return(cidr_list) end |
#arpa ⇒ Object
Synopsis
Depending on the IP version of the current CIDR, return either an in-addr.arpa. or ip6.arpa. string. The netmask will be used to determine the length of the returned string. Example: cidr = NetAddr::CIDR.create(‘192.168.1.1/24’) cidr.arpa => “1.168.192.in-addr.arpa.”
Arguments:
-
none
Returns:
-
String
534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 |
# File 'lib/cidr.rb', line 534 def arpa() base = self.ip() netmask = self.bits() if (@version == 4) net = base.split('.') if (netmask) while (netmask < 32) net.pop netmask = netmask + 8 end end arpa = net.reverse.join('.') arpa << ".in-addr.arpa." elsif (@version == 6) fields = base.split(':') net = [] fields.each do |field| (field.split("")).each do |x| net.push(x) end end if (netmask) while (netmask < 128) net.pop netmask = netmask + 4 end end arpa = net.reverse.join('.') arpa << ".ip6.arpa." end return(arpa) end |
#bits ⇒ Object
Synopsis
Provide number of bits in Netmask. Example: cidr = NetAddr::CIDR.create(‘192.168.1.1/24’) cidr.bits => 24
Arguments:
-
none
Returns:
-
Integer.
588 589 590 |
# File 'lib/cidr.rb', line 588 def bits() return(NetAddr.mask_to_bits(@netmask)) end |
#cmp(cidr) ⇒ Object
Synopsis
Compare the current CIDR with a provided CIDR and return:
-
1 if the current CIDR contains (is supernet of) the provided CIDR
-
0 if the current CIDR and the provided CIDR are equal (base address and netmask are equal)
-
-1 if the current CIDR is contained by (is subnet of) the provided CIDR
-
nil if the two CIDR addresses are unrelated
Example: cidr = NetAddr::CIDR.create(‘192.168.1.0/24’) cidr.cmp(‘192.168.1.0/25’) => 1 cidr.cmp(‘192.168.1.0/24’) => 0 cidr.cmp(‘192.168.0.0/23’) => -1 cidr.cmp(‘10.0.0.0/24’) => nil
Arguments:
-
CIDR address or NetAddr::CIDR object
Returns:
-
Integer or nil
612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 |
# File 'lib/cidr.rb', line 612 def cmp(cidr) if (!cidr.kind_of?(NetAddr::CIDR)) begin cidr = NetAddr::CIDR.create(cidr) rescue Exception => error raise ArgumentError, "Provided argument raised the following " + "errors: #{error}" end end if (cidr.version != @version) raise VersionError, "Attempted to compare a version #{cidr.version} CIDR " + "with a version #{@version} CIDR." end # compare comparasin = NetAddr.cidr_compare(self,cidr) return(comparasin) end |
#contains?(cidr) ⇒ Boolean
Synopsis
Determines if this CIDR contains (is supernet of) the provided CIDR address or NetAddr::CIDR object.
Example: cidr4 = NetAddr::CIDR.create(‘192.168.1.0/24’) cidr6 = NetAddr::CIDR.create(‘fec0::/64’) cidr6_2 = NetAddr::CIDR.create(‘fec0::/96’) cidr4.contains?(‘192.168.1.2’) => true cidr6.contains?(cidr6_2) => true
Arguments:
-
cidr = CIDR address or NetAddr::CIDR object
Returns:
-
true or false
650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 |
# File 'lib/cidr.rb', line 650 def contains?(cidr) contains = false if (!cidr.kind_of?(NetAddr::CIDR)) begin cidr = NetAddr::CIDR.create(cidr) rescue Exception => error raise ArgumentError, "Provided argument raised the following " + "errors: #{error}" end end if (cidr.version != @version) raise VersionError, "Attempted to compare a version #{cidr.version} CIDR " + "with a version #{@version} CIDR." end contains = true if ( NetAddr.cidr_compare(self,cidr) == 1 ) return(contains) end |
#desc(options = nil) ⇒ Object
Synopsis
See to_s
675 676 677 |
# File 'lib/cidr.rb', line 675 def desc(=nil) to_s() end |
#enumerate(options = nil) ⇒ Object
Synopsis
Provide all IP addresses contained within the IP space of this CIDR.
Example: cidr4 = NetAddr::CIDR.create(‘192.168.1.1/24’) cidr6 = NetAddr::CIDR.create(‘fec0::/64’) cidr4.enumerate(:Limit => 4, :Bitstep => 32) cidr6.enumerate(:Limit => 4, :Bitstep => 32, :Objectify => true)
Arguments:
-
options = Hash with the following keys:
:Bitstep -- enumerate in X sized steps - Integer :Limit -- limit returned list to X number of items - Integer :Objectify -- if true, return NetAddr::CIDR objects :Short -- if true, return IPv6 addresses in short-hand notation
Returns:
-
Array of Strings, or Array of NetAddr::CIDR objects
698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 |
# File 'lib/cidr.rb', line 698 def enumerate(=nil) known_args = [:Bitstep, :Limit, :Objectify, :Short] bitstep = 1 objectify = false limit = nil short = false if () if (!.kind_of? Hash) raise ArgumentError, "Expected Hash, but #{options.class} provided." end NetAddr.validate_args(.keys,known_args) if( .has_key?(:Bitstep) ) bitstep = [:Bitstep] end if( .has_key?(:Objectify) && [:Objectify] == true ) objectify = true end if( .has_key?(:Limit) ) limit = [:Limit] end if( .has_key?(:Short) && [:Short] == true ) short = true end end list = [] my_ip = @network change_mask = @hostmask | my_ip until ( change_mask != (@hostmask | @network) ) if (!objectify) my_ip_s = NetAddr.ip_int_to_str(my_ip, @version) my_ip_s = NetAddr.shorten(my_ip_s) if (short && @version == 6) list.push( my_ip_s ) else list.push( NetAddr.cidr_build(@version,my_ip) ) end my_ip = my_ip + bitstep change_mask = @hostmask | my_ip if (limit) limit = limit - 1 break if (limit == 0) end end return(list) end |
#fill_in(list, options = nil) ⇒ Object
Synopsis
Given a list of subnets of the current CIDR, return a new list with any holes (missing subnets) filled in.
Example: cidr4 = NetAddr::CIDR.create(‘192.168.1.0/24’) cidr4.fill_in()
Arguments:
-
list = Array of CIDR addresses, or Array of NetAddr::CIDR objects
-
options = Hash with the following keys:
:Objectify -- if true, return NetAddr::CIDR objects :Short -- if true, return IPv6 addresses in short-hand notation
Returns:
-
Array of CIDR Strings, or an Array of NetAddr::CIDR objects
769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 |
# File 'lib/cidr.rb', line 769 def fill_in(list, =nil) known_args = [:Objectify, :Short] short = false objectify = false # validate list raise ArgumentError, "Array expected for argument 'list' but #{list.class} provided." if (!list.kind_of?(Array) ) # validate options if () raise ArgumentError, "Hash expected for argument 'options' but " + "#{options.class} provided." if (!.kind_of?(Hash) ) NetAddr.validate_args(.keys,known_args) if (.has_key?(:Short) && [:Short] == true) short = true end if (.has_key?(:Objectify) && [:Objectify] == true) objectify = true end end # validate each cidr and store in cidr_list cidr_list = [] list.each do |obj| if (!obj.kind_of?(NetAddr::CIDR)) begin obj = NetAddr::CIDR.create(obj) rescue Exception => error aise ArgumentError, "A provided CIDR raised the following " + "errors: #{error}" end end if (!obj.version == self.version) raise VersionError, "#{obj.desc(:Short => true)} is not a version #{self.version} address." end # make sure we contain the cidr if ( self.contains?(obj) == false ) raise "#{obj.desc(:Short => true)} does not fit " + "within the bounds of #{self.desc(:Short => true)}." end cidr_list.push(obj) end complete_list = NetAddr.cidr_fill_in(self,cidr_list) if (!objectify) subnets = [] complete_list.each {|entry| subnets.push(entry.desc(:Short => short))} return(subnets) else return(complete_list) end end |
#ip(options = nil) ⇒ Object
Synopsis
Provide original IP address passed during initialization.
Example: cidr = NetAddr::CIDR.create(‘192.168.1.1/24’) cidr.ip => “192.168.1.1”
Arguments:
-
options = Hash with the following keys:
:Objectify -- if true, return NetAddr::CIDR object :Short -- if true, return IPv6 addresses in short-hand notation
Returns:
-
String or NetAddr::CIDR object.
841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 |
# File 'lib/cidr.rb', line 841 def ip(=nil) known_args = [:Objectify, :Short] objectify = false short = false if () if (!.kind_of?(Hash)) raise ArgumentError, "Expected Hash, but " + "#{options.class} provided." end NetAddr.validate_args(.keys,known_args) if( .has_key?(:Short) && [:Short] == true ) short = true end if( .has_key?(:Objectify) && [:Objectify] == true ) objectify = true end end if (!objectify) ip = NetAddr.ip_int_to_str(@ip, @version) ip = NetAddr.shorten(ip) if (short && @version == 6) else ip = NetAddr.cidr_build(@version,@ip) end return(ip) end |
#is_contained?(cidr) ⇒ Boolean
Synopsis
Determines if this CIDR is contained within (is subnet of) the provided CIDR address or NetAddr::CIDR object.
Example: cidr4 = NetAddr::CIDR.create(‘192.168.1.1/24’) cidr4.is_contained?(‘192.168.0.0/23’)
Arguments:
-
cidr = CIDR address or NetAddr::CIDR object
Returns:
-
true or false
887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 |
# File 'lib/cidr.rb', line 887 def is_contained?(cidr) is_contained = false if (!cidr.kind_of?(NetAddr::CIDR)) begin cidr = NetAddr::CIDR.create(cidr) rescue Exception => error raise ArgumentError, "Provided argument raised the following " + "errors: #{error}" end end if (cidr.version != @version) raise VersionError, "Attempted to compare a version #{cidr.version} CIDR " + "with a version #{@version} CIDR." end network = cidr.to_i(:network) netmask = cidr.to_i(:netmask) hostmask = cidr.to_i(:hostmask) is_contained = true if ( NetAddr.cidr_compare(self,cidr) == -1 ) return(is_contained) end |
#last(options = nil) ⇒ Object
Synopsis
Provide last IP address in this CIDR object.
Example: cidr = NetAddr::CIDR.create(‘192.168.1.0/24’) cidr.last => “192.168.1.255”
Arguments:
-
options = Hash with the following keys:
:Objectify -- if true, return NetAddr::CIDR object :Short -- if true, return IPv6 addresses in short-hand notation
Returns:
-
String or NetAddr::CIDR object.
928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 |
# File 'lib/cidr.rb', line 928 def last(=nil) known_args = [:Objectify, :Short] objectify = false short = false if () if (!.kind_of?(Hash)) raise ArgumentError, "Expected Hash, but " + "#{options.class} provided." end NetAddr.validate_args(.keys,known_args) if( .has_key?(:Short) && [:Short] == true ) short = true end if( .has_key?(:Objectify) && [:Objectify] == true ) objectify = true end end ip_int = @network | @hostmask if (!objectify) ip = NetAddr.ip_int_to_str(ip_int, @version) ip = NetAddr.shorten(ip) if (short && !objectify && @version == 6) else ip = NetAddr.cidr_build(@version,ip_int) end return(ip) end |
#matches?(ip) ⇒ Boolean
Synopsis
Given an IP address (or if a NetAddr::CIDR object, then the original IP of that object), determine if it falls within the range of addresses resulting from the combination of the IP and Wildcard Mask of this CIDR.
Example: cidr4 = NetAddr.CIDRv4.create(‘10.0.0.0’, :WildcardMask => [‘0.7.0.255’, true]) cidr4.matches?(‘10.0.0.22’) -> true cidr4.matches?(‘10.8.0.1’) -> false cidr4.matches?(‘10.1.0.1’) -> true cidr4.matches?(‘10.0.1.22’) -> false
Arguments:
-
ip = IP address as a String or a CIDR object
Returns:
-
True or False
979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 |
# File 'lib/cidr.rb', line 979 def matches?(ip) ip_int = nil if (!ip.kind_of?(NetAddr::CIDR)) begin ip_int = NetAddr.ip_to_i(ip, :Version => @version) rescue NetAddr::ValidationError raise NetAddr::ValidationError, "Provided IP must be a valid IPv#{@version} address." end else raise NetAddr::ValidationError, "Provided CIDR must be of type #{self.class}" if (ip.class != self.class) ip_int = ip.to_i(:ip) end return(true) if (@ip & @wildcard_mask == ip_int & @wildcard_mask) return(false) end |
#multicast_mac(options = nil) ⇒ Object
Synopsis
Assuming this CIDR is a valid multicast address (224.0.0.0/4 for IPv4 and ff00::/8 for IPv6), return its ethernet MAC address (EUI-48) mapping. MAC address is based on original IP address passed during initialization.
Example: mcast = NetAddr::CIDR.create(‘224.0.0.6’) mcast.multicast_mac.address
Arguments:
-
options = Hash with the following keys:
:Objectify -- if true, return EUI objects
Returns:
-
String or NetAddr::EUI48 object
1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 |
# File 'lib/cidr.rb', line 1012 def multicast_mac(=nil) known_args = [:Objectify] objectify = false if () if (!.kind_of? Hash) raise ArgumentError, "Expected Hash, but #{options.class} provided." end NetAddr.validate_args(.keys,known_args) if (.has_key?(:Objectify) && [:Objectify] == true) objectify = true end end if (@version == 4) if (@ip & 0xf0000000 == 0xe0000000) # map low order 23-bits of ip to 01:00:5e:00:00:00 mac = @ip & 0x007fffff | 0x01005e000000 else raise ValidationError, "#{self.ip} is not a valid multicast address. IPv4 multicast " + "addresses should be in the range 224.0.0.0/4." end else if (@ip & (0xff << 120) == 0xff << 120) # map low order 32-bits of ip to 33:33:00:00:00:00 mac = @ip & (2**32-1) | 0x333300000000 else raise ValidationError, "#{self.ip} is not a valid multicast address. IPv6 multicast " + "addresses should be in the range ff00::/8." end end eui = NetAddr::EUI48.new(mac) eui = eui.address if (!objectify) return(eui) end |
#netmask ⇒ Object
Synopsis
Provide netmask in CIDR format (/yy).
Example: cidr = NetAddr::CIDR.create(‘192.168.1.0/24’) cidr.netmask => “/24”
Arguments:
-
none
Returns:
-
String
1064 1065 1066 1067 |
# File 'lib/cidr.rb', line 1064 def netmask() bits = NetAddr.mask_to_bits(@netmask) return("/#{bits}") end |
#network(options = nil) ⇒ Object Also known as: base, first
Synopsis
Provide base network address.
Example: cidr = NetAddr::CIDR.create(‘192.168.1.0/24’) cidr.network => “192.168.1.0”
Arguments:
-
options = Hash with the following fields:
:Objectify -- if true, return NetAddr::CIDR object :Short -- if true, return IPv6 addresses in short-hand notation
Returns:
-
String or NetAddr::CIDR object.
1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 |
# File 'lib/cidr.rb', line 1084 def network(=nil) known_args = [:Objectify, :Short] objectify = false short = false if () if (!.kind_of?(Hash)) raise ArgumentError, "Expected Hash, but " + "#{options.class} provided." end NetAddr.validate_args(.keys,known_args) if( .has_key?(:Short) && [:Short] == true ) short = true end if( .has_key?(:Objectify) && [:Objectify] == true ) objectify = true end end if (!objectify) ip = NetAddr.ip_int_to_str(@network, @version) ip = NetAddr.shorten(ip) if (short && @version == 6) else ip = NetAddr.cidr_build(@version,@network) end return(ip) end |
#next_ip(options = nil) ⇒ Object
Synopsis
Provide the next IP following the last available IP within this CIDR object.
Example: cidr4 = NetAddr::CIDR.create(‘192.168.1.1/24’) cidr6 = NetAddr::CIDR.create(‘fec0::/64’) cidr4.next_subnet() cidr6.next_subnet(:Short => true)}
Arguments:
-
options = Hash with the following keys:
:Bitstep -- step in X sized steps - Integer :Objectify -- if true, return NetAddr::CIDR object :Short -- if true, return IPv6 addresses in short-hand notation
Returns:
-
String or NetAddr::CIDR object.
1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 |
# File 'lib/cidr.rb', line 1137 def next_ip(=nil) known_args = [:Bitstep, :Objectify, :Short] bitstep = 1 objectify = false short = false if () if (!.kind_of?(Hash)) raise ArgumentError, "Expected Hash, but " + "#{options.class} provided." end NetAddr.validate_args(.keys,known_args) if( .has_key?(:Bitstep) ) bitstep = [:Bitstep] end if( .has_key?(:Short) && [:Short] == true ) short = true end if( .has_key?(:Objectify) && [:Objectify] == true ) objectify = true end end next_ip = @network + @hostmask + bitstep if (next_ip > @all_f) raise BoundaryError, "Returned IP is out of bounds for IPv#{@version}." end if (!objectify) next_ip = NetAddr.ip_int_to_str(next_ip, @version) next_ip = NetAddr.shorten(next_ip) if (short && @version == 6) else next_ip = NetAddr.cidr_build(@version,next_ip) end return(next_ip) end |
#next_subnet(options = nil) ⇒ Object
Synopsis
Provide the next subnet following this CIDR object. The next subnet will be of the same size as the current CIDR object.
Example: cidr4 = NetAddr::CIDR.create(‘192.168.1.1/24’) cidr6 = NetAddr::CIDR.create(‘fec0::/64’) cidr4.next_subnet() cidr6.next_subnet(:Short => true)
Arguments:
-
options = Hash with the following keys:
:Bitstep -- step in X sized steps. - Integer :Objectify -- if true, return NetAddr::CIDR object :Short -- if true, return IPv6 addresses in short-hand notation
Returns:
-
String or NetAddr::CIDR object.
1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 |
# File 'lib/cidr.rb', line 1199 def next_subnet(=nil) known_args = [:Bitstep, :Objectify, :Short] bitstep = 1 objectify = false short = false if () if (!.kind_of?(Hash)) raise ArgumentError, "Expected Hash, but " + "#{options.class} provided." end NetAddr.validate_args(.keys,known_args) if( .has_key?(:Bitstep) ) bitstep = [:Bitstep] end if( .has_key?(:Short) && [:Short] == true ) short = true end if( .has_key?(:Objectify) && [:Objectify] == true ) objectify = true end end bitstep = bitstep * (2**(@address_len - self.bits) ) next_sub = @network + bitstep if (next_sub > @all_f) raise BoundaryError, "Returned subnet is out of bounds for IPv#{@version}." end if (!objectify) next_sub = NetAddr.ip_int_to_str(next_sub, @version) next_sub = NetAddr.shorten(next_sub) if (short && @version == 6) next_sub = next_sub << "/" << self.bits.to_s else next_sub = NetAddr.cidr_build(@version,next_sub,self.to_i(:netmask)) end return(next_sub) end |
#nth(index, options = nil) ⇒ Object
Synopsis
Provide the nth IP within this object.
Example: cidr4 = NetAddr::CIDR.create(‘192.168.1.1/24’) cidr4.nth(1) cidr4.nth(1, :Objectify => true)
Arguments:
-
index = Index number as an Integer
-
options = Hash with the following keys:
:Objectify -- if true, return NetAddr::CIDR objects :Short -- if true, return IPv6 addresses in short-hand notation
Returns:
-
String or NetAddr::CIDR object.
1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 |
# File 'lib/cidr.rb', line 1260 def nth(index, =nil) known_args = [:Objectify, :Short] objectify = false short = false # validate list raise ArgumentError, "Integer expected for argument 'index' but " + "#{index.class} provided." if (!index.kind_of?(Integer) ) # validate options if () raise ArgumentError, "Hash expected for argument 'options' but #{options.class} provided." if (!.kind_of?(Hash) ) NetAddr.validate_args(.keys,known_args) if( .has_key?(:Short) && [:Short] == true ) short = true end if( .has_key?(:Objectify) && [:Objectify] == true ) objectify = true end end my_ip = @network + index if ( (@hostmask | my_ip) == (@hostmask | @network) ) if (!objectify) my_ip = NetAddr.ip_int_to_str(my_ip, @version) my_ip = NetAddr.shorten(my_ip) if (short && @version == 6) else my_ip = NetAddr.cidr_build(@version,my_ip) end else raise BoundaryError, "Index of #{index} returns IP that is out of " + "bounds of CIDR network." end return(my_ip) end |
#range(lower, upper = nil, options = nil) ⇒ Object
Synopsis
Given a set of index numbers for this CIDR, return all IP addresses within the CIDR that are between them (inclusive). If an upper bound is not provided, then all addresses from the lower bound up will be returned.
Example: cidr4 = NetAddr::CIDR.create(‘192.168.1.1/24’) cidr4.range(0, 1) cidr4.range(0, 1, :Objectify => true) cidr4.range(0, nil, :Objectify => true)
Arguments:
-
lower = Lower range boundary index as an Integer
-
upper = Upper range boundary index as an Integer
-
options = Hash with the following keys:
:Bitstep -- enumerate in X sized steps - Integer :Objectify -- if true, return NetAddr::CIDR objects :Short -- if true, return IPv6 addresses in short-hand notation
Returns:
-
Array of Strings, or Array of NetAddr::CIDR objects
Note:
If you do not need all of the fancy options in this method, then please consider using the standard Ruby Range class as shown below.
Example: start = NetAddr::CIDR.create(‘192.168.1.0’) fin = NetAddr::CIDR.create(‘192.168.2.3’) (start..fin).each {|addr| puts addr.desc}
1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 |
# File 'lib/cidr.rb', line 1332 def range(lower, upper=nil, =nil) known_args = [:Bitstep, :Objectify, :Short] objectify = false short = false bitstep = 1 # validate indexes raise ArgumentError, "Integer expected for argument 'lower' " + "but #{lower.class} provided." if (!lower.kind_of?(Integer)) raise ArgumentError, "Integer expected for argument 'upper' " + "but #{upper.class} provided." if (upper && !upper.kind_of?(Integer)) upper = @hostmask if (upper.nil?) indexes = [lower,upper] indexes.sort! if ( (indexes[0] < 0) || (indexes[0] > self.size) ) raise BoundaryError, "Index #{indexes[0]} is out of bounds for this CIDR." end if (indexes[1] >= self.size) raise BoundaryError, "Index #{indexes[1]} is out of bounds for this CIDR." end # validate options if () raise ArgumentError, "Hash expected for argument 'options' but #{options.class} provided." if (!.kind_of?(Hash) ) NetAddr.validate_args(.keys,known_args) if( .has_key?(:Short) && [:Short] == true ) short = true end if( .has_key?(:Objectify) && [:Objectify] == true ) objectify = true end if( .has_key?(:Bitstep) ) bitstep = [:Bitstep] end end # make range start_ip = @network + indexes[0] end_ip = @network + indexes[1] my_ip = start_ip list = [] until (my_ip > end_ip) if (!objectify) ip = NetAddr.ip_int_to_str(my_ip, @version) ip = NetAddr.shorten(ip) if (short && @version == 6) else ip = NetAddr.cidr_build(@version,my_ip) end list.push(ip) my_ip += bitstep end return(list) end |
#remainder(addr, options = nil) ⇒ Object
Synopsis
Given a single subnet of the current CIDR, provide the remainder of the subnets. For example if the original CIDR is 192.168.0.0/24 and you provide 192.168.0.64/26 as the portion to exclude, then 192.168.0.0/26, and 192.168.0.128/25 will be returned as the remainders.
cidr4 = NetAddr::CIDR.create(‘192.168.1.0/24’) cidr4.remainder(‘192.168.1.32/27’) cidr4.remainder(‘192.168.1.32/27’, :Objectify => true)
Arguments:
-
addr = CIDR address or NetAddr::CIDR object
-
options = Hash with the following keys:
:Objectify -- if true, return NetAddr::CIDR objects :Short -- if true, return IPv6 addresses in short-hand notation
Returns:
-
Array of Strings, or Array of NetAddr::CIDR objects
1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 |
# File 'lib/cidr.rb', line 1413 def remainder(addr, =nil) known_args = [:Objectify, :Short] short = nil objectify = nil # validate options if () raise ArgumentError, "Hash expected for argument 'options' but " + "#{options.class} provided." if (!.kind_of?(Hash) ) NetAddr.validate_args(.keys,known_args) if( .has_key?(:Short) && [:Short] == true ) short = true end if( .has_key?(:Objectify) && [:Objectify] == true ) objectify = true end end if ( !addr.kind_of?(NetAddr::CIDR) ) begin addr = NetAddr::CIDR.create(addr) rescue Exception => error raise ArgumentError, "Argument 'addr' raised the following " + "errors: #{error}" end end # make sure 'addr' is the same ip version if ( addr.version != @version ) raise VersionError, "#{addr.desc(:Short => true)} is of a different " + "IP version than #{self.desc(:Short => true)}." end # make sure we contain 'to_exclude' if ( self.contains?(addr) != true ) raise BoundaryError, "#{addr.desc(:Short => true)} does not fit " + "within the bounds of #{self.desc(:Short => true)}." end # split this cidr in half & see which half 'to_exclude' # belongs in. take that half & repeat the process. every time # we repeat, store the non-matching half new_mask = self.bits + 1 lower_network = self.to_i(:network) upper_network = self.to_i(:network) + 2**(@address_len - new_mask) new_subnets = [] until(new_mask > addr.bits) if (addr.to_i(:network) < upper_network) match = lower_network non_match = upper_network else match = upper_network non_match = lower_network end if (!objectify) non_match = NetAddr.ip_int_to_str(non_match, @version) non_match = NetAddr.shorten(non_match) if (short && @version == 6) new_subnets.unshift("#{non_match}/#{new_mask}") else new_subnets.unshift( NetAddr.cidr_build(@version, non_match, NetAddr.bits_to_mask(new_mask,version) ) ) end new_mask = new_mask + 1 lower_network = match upper_network = match + 2**(@address_len - new_mask) end return(new_subnets) end |
#resize(bits) ⇒ Object
Synopsis
Resize the CIDR by changing the size of the Netmask. Return the resulting CIDR as a new object.
Example: cidr4 = NetAddr::CIDR.create(‘192.168.1.1/24’) new_cidr = cidr4.resize(23)
Arguments:
-
bits = Netmask as an Integer
Returns:
-
NetAddr::CIDR object
1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 |
# File 'lib/cidr.rb', line 1502 def resize(bits) raise ArgumentError, "Integer or Hash expected, but " + "#{bits.class} provided." if (!bits.kind_of?(Integer)) NetAddr.validate_ip_netmask(bits, :Version => @version) netmask = NetAddr.bits_to_mask(bits, @version) network = @network & netmask return( NetAddr.cidr_build(@version, network, netmask) ) end |
#resize!(bits) ⇒ Object
Synopsis
Resize the current CIDR by changing the size of the Netmask. The original IP passed during initialization will be set to the base network address if it no longer falls within the bounds of the CIDR.
Example: cidr4 = NetAddr::CIDR.create(‘192.168.1.1/24’) cidr4.resize!(23)
Arguments:
-
bits = Netmask as an Integer
Returns:
-
True
1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 |
# File 'lib/cidr.rb', line 1528 def resize!(bits) raise ArgumentError, "Integer or Hash expected, but " + "#{bits.class} provided." if (!bits.kind_of?(Integer)) NetAddr.validate_ip_netmask(bits, :Version => @version) netmask = NetAddr.netmask_to_i(bits, :Version => @version) @netmask = netmask @network = @network & netmask @hostmask = @netmask ^ @all_f # check @ip if ((@ip & @netmask) != (@network)) @ip = @network end return(true) end |
#set_wildcard_mask(mask, bit_flipped = false) ⇒ Object
Synopsis
Set the wildcard mask. Wildcard masks are typically used for matching entries in an access-list.
Example: cidr4 = NetAddr::CIDR.create(‘192.168.1.0/24’) cidr4.set_wildcard_mask(‘0.0.0.255’, true) cidr4.set_wildcard_mask(‘255.255.255.0’)
Arguments:
-
mask = wildcard mask as a String or Integer
-
bit_flipped = if set True then the wildcard mask is interpereted as bit-flipped.
Returns:
-
nil
1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 |
# File 'lib/cidr.rb', line 1563 def set_wildcard_mask(mask, bit_flipped=false) netmask_int = nil if (mask.kind_of?(Integer)) NetAddr.validate_ip_int(mask,@version) netmask_int = mask else begin NetAddr.validate_ip_str(mask,@version) netmask_int = NetAddr.ip_str_to_int(mask, @version) rescue NetAddr::ValidationError raise NetAddr::ValidationError, "Wildcard Mask must be a valid IPv#{@version} address." end end netmask_int = ~netmask_int if (bit_flipped) @wildcard_mask = netmask_int return(nil) end |
#size ⇒ Object
Synopsis
Provide number of IP addresses within this CIDR.
Example: cidr = NetAddr::CIDR.create(‘192.168.1.0/24’) cidr.size => 256
Arguments:
-
none
Returns:
-
Integer
1595 1596 1597 |
# File 'lib/cidr.rb', line 1595 def size() return(@hostmask + 1) end |
#subnet(options = nil) ⇒ Object
Synopsis
Create subnets for this CIDR. There are 2 ways to create subnets:
* By providing the netmask (in bits) of the new subnets with :Bits.
* By providing the number of IP addresses needed in the new subnets with :IPCount
:NumSubnets is used to determine how the CIDR is subnetted. For example, if I request the following operation:
NetAddr::CIDR.create(‘192.168.1.0/24’).subnet(:Bits => 26, :NumSubnets => 1)
then I would get back the first /26 subnet of 192.168.1.0/24 and the remainder of the IP space as summary CIDR addresses (e.g. 192.168.1.0/26, 192.168.1.64/26, and 192.168.1.128/25). If I were to perform the same operation without the :NumSubnets directive, then 192.168.1.0/24 will be fully subnetted into X number of /26 subnets (e.g. 192.168.1.0/26, 192.168.1.64/26, 192.168.1.128/26, and 192.168.1.192/26).
If neither :Bits nor :IPCount is provided, then the current CIDR will be split in half. If both :Bits and :IPCount are provided, then :Bits takes precedence.
Example: cidr4 = NetAddr::CIDR.create(‘192.168.1.0/24’) cidr6 = NetAddr::CIDR.create(‘fec0::/64’) cidr4.subnet(:Bits => 28, :NumSubnets => 3) cidr4.subnet(:IPCount => 19) cidr4.subnet(:Bits => 28) cidr6.subnet(:Bits => 67, :NumSubnets => 4, :Short => true)
Arguments:
-
options = Hash with the following keys:
:Bits -- Netmask (in bits) of new subnets - Integer :IPCount -- Minimum number of IP's that new subnets should contain - Integer :NumSubnets -- Number of X sized subnets to return - Integer :Objectify -- if true, return NetAddr::CIDR objects :Short -- if true, return IPv6 addresses in short-hand notation
Returns:
-
Array of Strings, or Array of NetAddr::CIDR objects
1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 |
# File 'lib/cidr.rb', line 1637 def subnet(=nil) known_args = [:Bits, :IPCount, :NumSubnets, :Objectify, :Short] my_network = self.to_i(:network) my_mask = self.bits subnet_bits = my_mask + 1 min_count = nil objectify = false short = false if () if (!.kind_of? Hash) raise ArgumentError, "Expected Hash, but #{options.class} provided." end NetAddr.validate_args(.keys,known_args) if ( .has_key?(:IPCount) ) subnet_bits = NetAddr.ip_count_to_size([:IPCount], @version) end if ( .has_key?(:Bits) ) subnet_bits = [:Bits] end if ( .has_key?(:NumSubnets) ) num_subnets = [:NumSubnets] end if( .has_key?(:Short) && [:Short] == true ) short = true end if( .has_key?(:Objectify) && [:Objectify] == true ) objectify = true end end # get number of subnets possible with the requested subnet_bits num_avail = 2**(subnet_bits - my_mask) # get the number of bits in the next supernet and # make sure num_subnets is a power of 2 bits_needed = 1 num_subnets = num_avail if (!num_subnets) until (2**bits_needed >= num_subnets) bits_needed += 1 end num_subnets = 2**bits_needed next_supernet_bits = subnet_bits - bits_needed # make sure subnet isnt bigger than available bits if (subnet_bits > @address_len) raise BoundaryError, "Requested subnet (#{subnet_bits}) does not fit " + "within the bounds of IPv#{@version}." end # make sure subnet is larger than mymask if (subnet_bits < my_mask) raise BoundaryError, "Requested subnet (#{subnet_bits}) is too large for " + "current CIDR space." end # make sure MinCount is smaller than available subnets if (num_subnets > num_avail) raise "Requested subnet count (#{num_subnets}) exceeds subnets " + "available for allocation (#{num_avail})." end # list all 'subnet_bits' sized subnets of this cidr block # with a limit of num_subnets bitstep = 2**(@address_len - subnet_bits) subnets = self.enumerate(:Bitstep => bitstep, :Limit => num_subnets, :Objectify => true) # save our subnets new_subnets = [] subnets.each do |subnet| if (!objectify) if (short && @version == 6) new_subnets.push("#{subnet.network(:Short => true)}/#{subnet_bits}") else new_subnets.push("#{subnet.network}/#{subnet_bits}") end else new_subnets.push( NetAddr.cidr_build(@version, subnet.to_i(:network), NetAddr.bits_to_mask(subnet_bits,version) ) ) end end # now go through the rest of the cidr space and make the rest # of the subnets. we want these to be as tightly merged as possible next_supernet_bitstep = (bitstep * num_subnets) next_supernet_ip = my_network + next_supernet_bitstep until (next_supernet_bits == my_mask) if (!objectify) next_network = NetAddr.ip_int_to_str(next_supernet_ip, @version) next_network = NetAddr.shorten(next_network) if (short && @version == 6) new_subnets.push("#{next_network}/#{next_supernet_bits}") else new_subnets.push(NetAddr.cidr_build(@version, next_supernet_ip, NetAddr.bits_to_mask(next_supernet_bits,version) ) ) end next_supernet_bits -= 1 next_supernet_ip = next_supernet_ip + next_supernet_bitstep next_supernet_bitstep = next_supernet_bitstep << 1 end return(new_subnets) end |
#succ ⇒ Object
Synopsis
Provide the next subnet following this CIDR object. The next subnet will be of the same size as the current CIDR object.
Example: cidr = NetAddr::CIDR.create(‘192.168.1.0/24’) cidr.succ => 192.168.2.0/24
Arguments:
-
none
Returns:
-
NetAddr::CIDR object.
1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 |
# File 'lib/cidr.rb', line 1760 def succ() bitstep = 2**(@address_len - self.bits) next_sub = @network + bitstep if (next_sub > @all_f) raise BoundaryError, "Returned subnet is out of bounds for IPv#{@version}." end next_sub = NetAddr.cidr_build(@version,next_sub,self.to_i(:netmask)) return(next_sub) end |
#to_i(attribute = :network) ⇒ Object
Synopsis
Convert the requested attribute of the CIDR to an Integer. Example: cidr = NetAddr::CIDR.create(‘192.168.1.1/24’) cidr.to_i => 3232235776 cidr.to_i(:hostmask) => 255 cidr.to_i(:ip) => 3232235777 cidr.to_i(:netmask) => 4294967040 cidr.to_i(:wildcard_mask) => 4294967040
Arguments:
-
attribute – attribute of the CIDR to convert to an Integer (:hostmask, :ip, :netmask, :network, or :wildcard_mask).
Returns:
-
Integer
1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 |
# File 'lib/cidr.rb', line 1789 def to_i(attribute=:network) if(attribute == :network) return(@network) elsif(attribute == :hostmask) return(@hostmask) elsif(attribute == :ip) return(@ip) elsif(attribute == :netmask) return(@netmask) elsif(attribute == :wildcard_mask) return(@wildcard_mask) else raise ArgumentError, "Attribute is unrecognized. Must be :hostmask, :ip, :netmask, :network, or :wildcard_mask." end end |
#to_s(options = nil) ⇒ Object
Synopsis
Returns network/netmask in CIDR format.
Example: cidr4 = NetAddr::CIDR.create(‘192.168.1.1/24’) cidr6 = NetAddr::CIDR.create(‘fec0::/64’) cidr4.desc(:IP => true) => “192.168.1.1/24” cidr4.to_s => “192.168.1.0/24” cidr6.to_s(:Short => true) => “fec0::/64”
Arguments:
-
options = Optional hash with the following keys:
:IP -- if true, return the original ip/netmask passed during initialization :Short -- if true, return IPv6 addresses in short-hand notation
Returns:
-
String
1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 |
# File 'lib/cidr.rb', line 1823 def to_s(=nil) known_args = [:IP, :Short] short = false orig_ip = false if () if (!.kind_of? Hash) raise ArgumentError, "Expected Hash, but #{options.class} provided." end NetAddr.validate_args(.keys,known_args) if (.has_key?(:Short) && [:Short] == true) short = true end if (.has_key?(:IP) && [:IP] == true) orig_ip = true end end if (!orig_ip) ip = NetAddr.ip_int_to_str(@network, @version) else ip = NetAddr.ip_int_to_str(@ip, @version) end ip = NetAddr.shorten(ip) if (short && @version == 6) mask = NetAddr.mask_to_bits(@netmask) return("#{ip}/#{mask}") end |
#wildcard_mask(bit_flipped = false) ⇒ Object
Synopsis
Return the wildcard mask.
Example: cidr = NetAddr::CIDR.create(‘10.1.0.0/24’, :WildcardMask => [‘0.7.0.255’, true]) cidr.wildcard_mask => “255.248.255.0” cidr.wildcard_mask(true) => “0.7.0.255”
Arguments:
-
bit_flipped = if set True then returned the bit-flipped version of the wildcard mask.
Returns:
-
String
1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 |
# File 'lib/cidr.rb', line 1868 def wildcard_mask(bit_flipped=false) ret_val = nil if (!bit_flipped) ret_val = NetAddr.ip_int_to_str(@wildcard_mask, @version) else ret_val = NetAddr.ip_int_to_str(~@wildcard_mask, @version) end return(ret_val) end |