Class: NetAddr::CIDR

Inherits:
Object
  • Object
show all
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.

Direct Known Subclasses

CIDRv4, CIDRv6

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#all_fObject (readonly)

Integer of either 32 or 128 bits in length, with all bits set to 1



55
56
57
# File 'lib/cidr.rb', line 55

def all_f
  @all_f
end

#tagObject

Hash of custom tags. Should be in the format tag => value.



52
53
54
# File 'lib/cidr.rb', line 52

def tag
  @tag
end

#versionObject (readonly)

IP version 4 or 6.



49
50
51
# File 'lib/cidr.rb', line 49

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. :PackedNetmask takes precedence over netmask given within CIDR addresses. Version will be auto-detected if not specified.

cidr4 = NetAddr::CIDR.create(‘192.168.1.1/24’) cidr4 = NetAddr::CIDR.create(‘192.168.1.1 255.255.255.0’) cidr4_2 = NetAddr::CIDR.create(0x0a010001,

:PackedNetmask => 0xffffff00
:Version => 4)

cidr4_3 = NetAddr::CIDRv4.new(‘192.168.1.1’,

:WildcardMask => ['0.7.0.255', :inversed])

cidr4_4 = NetAddr::CIDRv4.new(‘192.168.5.0’,

:WildcardMask => ['255.248.255.0'])

cidr6 = NetAddr::CIDR.create(‘fec0::/64’) cidr6 = NetAddr::CIDR.create(‘fec0::/64’,

:Tag => {'interface' => 'g0/1'})

cidr6_2 = NetAddr::CIDR.create(‘::ffff:192.168.1.1/96’)

Arguments:

  • CIDR address as a String, or a packed IP address as an Integer

  • Optional Hash with the following keys:

    :PackedNetmask -- Integer representation of an IP Netmask (optional)
    :Version -- IP version - Integer (optional)
    :Tag -- Custom descriptor tag - Hash, tag => value. (optional)
    :WildcardMask -- 2 element Array. First element contains a special bit mask used for
                     advanced IP pattern matching. The second element should be :inversed if this
                     bit mask is in inverse format. (optional)
    


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
# File 'lib/cidr.rb', line 105

def CIDR.create(addr, options=nil)
    known_args = [:PackedNetmask, :Version, :Tag, :WildcardMask]
    cidr = nil
    packed_ip = nil
    version = nil

    # validate addr arg
    if (addr.kind_of?(String))
        cidr = addr
    elsif (addr.kind_of?(Integer))
        packed_ip = addr
    else
        raise ArgumentError, "String or Integer expected for argument 'addr' but #{addr.class} provided."
    end

    # validate options
    if (options)     
        raise ArgumentError, "Hash expected for argument 'options' but " +
                             "#{options.class} provided." if (!options.kind_of?(Hash) )
        NetAddr.validate_args(options.keys,known_args)
        if (options.has_key?(:Version))
            version = options[:Version]
            options.delete(:Version)
            if (version != 4 && version != 6)
                raise VersionError, ":Version should be 4 or 6, but was '#{version}'."
            end
        end
    end

    # attempt to determine version if not provided
    if (!version)
        if (packed_ip) 
            if (packed_ip < 2**32)
                version = 4
            else
                version = 6
            end
        else
            if (cidr =~ /\./ && cidr !~ /:/)
                version = 4
            elsif (cidr =~ /:/)
                version = 6
            end
        end
    end

    # create CIDRvX object
    if (version == 4)
        return(NetAddr::CIDRv4.new(addr, options))
    elsif (version == 6)
        return(NetAddr::CIDRv6.new(addr, options))
    else
        raise ArgumentError, "IP version omitted or could not be detected."
    end

end

Instance Method Details

#arpaObject

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.

cidr4 = NetAddr::CIDR.create(‘192.168.1.1/24’) cidr6 = NetAddr::CIDR.create(‘fec0::/64’) puts “arpa for #NetAddr::CIDR.cidr4cidr4.desc() is #NetAddr::CIDR.cidr4cidr4.arpa” puts “arpa for #=> true) is #NetAddr::CIDR.cidr6cidr6.arpa”

Arguments:

  • none

Returns:

  • String



182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
# File 'lib/cidr.rb', line 182

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

#bitsObject

Synopsis

Provide number of bits in Netmask.

cidr4 = NetAddr::CIDR.create(‘192.168.1.1/24’) cidr6 = NetAddr::CIDR.create(‘fec0::/64’) puts “cidr4 netmask in bits #NetAddr::CIDR.cidr4cidr4.bits()” puts “cidr6 netmask in bits #NetAddr::CIDR.cidr6cidr6.bits()”

Arguments:

  • none

Returns:

  • Integer.



242
243
244
# File 'lib/cidr.rb', line 242

def bits()
    return(NetAddr.unpack_ip_netmask(@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

cidr4 = NetAddr::CIDR.create(‘192.168.1.0/24’) cidr4_2 = NetAddr::CIDR.create(‘192.168.1.0/26’) comp1 = cidr4.cmp(cidr4_2) comp2 = cidr4.cmp(‘192.168.1.0/26’)

Arguments:

  • CIDR address or NetAddr::CIDR object

Returns:

  • Integer or nil



268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
# File 'lib/cidr.rb', line 268

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 = nil
        if ( (@network == cidr.packed_network))
            if (@netmask == cidr.packed_netmask)
                comparasin = 0
            elsif(@netmask < cidr.packed_netmask)
                comparasin = 1
            elsif(@netmask > cidr.packed_netmask)
                comparasin = -1            
            end
        
        elsif( (cidr.packed_network | @hostmask) == (@network | @hostmask) )
            comparasin = 1
        elsif( (cidr.packed_network | cidr.packed_hostmask) == (@network | cidr.packed_hostmask) )
            comparasin = -1
        end

    return(comparasin)
end

#contains?(cidr) ⇒ Boolean

Synopsis

Determines if this CIDR contains (is supernet of) the provided CIDR address or NetAddr::CIDR object.

cidr4 = NetAddr::CIDR.create(‘192.168.1.1/24’) cidr6 = NetAddr::CIDR.create(‘fec0::/64’) cidr6_2 = NetAddr::CIDR.create(‘fec0::/96’) puts “#NetAddr::CIDR.cidr4cidr4.desc contains 192.168.1.2” if ( cidr4.contains?(‘192.168.1.2’) ) puts “#NetAddr::CIDR.cidr6cidr6.desc contains #=> true)” if ( cidr6.contains?(cidr6_2) )

Arguments:

  • CIDR address or NetAddr::CIDR object

Returns:

  • true or false

Returns:

  • (Boolean)


323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
# File 'lib/cidr.rb', line 323

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
    
    network = cidr.packed_network 
    netmask = cidr.packed_netmask


    if (cidr.version != @version)
        raise VersionError, "Attempted to compare a version #{cidr.version} CIDR " +
                             "with a version #{@version} CIDR."
    end

    # if network == @network, then we have to go by netmask length
    # else we can tell by or'ing network and @network by @hostmask
    # and comparing the results
    if (network == @network)
        contains = true if (netmask > @netmask)

    else
        if ( (network | @hostmask) == (@network | @hostmask) )
            contains = true
        end
    end

    return(contains)
end

#desc(options = nil) ⇒ Object

Synopsis

Returns network/netmask in CIDR format.

cidr4 = NetAddr::CIDR.create(‘192.168.1.1/24’) cidr6 = NetAddr::CIDR.create(‘fec0::/64’) puts cidr4.desc(:IP => true) puts “cidr4 description #NetAddr::CIDR.cidr4cidr4.desc()” puts “cidr6 description #NetAddr::CIDR.cidr6cidr6.desc()” puts “cidr6 short-hand description #=> true)”

Arguments:

  • Optional hash with the following keys:

    :IP -- if true, return the original ip/netmask passed during initialization (optional)
    :Short -- if true, return IPv6 addresses in short-hand notation (optional)
    

Returns:

  • String



381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
# File 'lib/cidr.rb', line 381

def desc(options=nil)
    known_args = [:IP, :Short]
    short = false
    orig_ip = false

    if (options)
        if (!options.kind_of? Hash)
            raise ArgumentError, "Expected Hash, but #{options.class} provided."
        end
        NetAddr.validate_args(options.keys,known_args)
        
        if (options.has_key?(:Short) && options[:Short] == true)
            short = true
        end
        
        if (options.has_key?(:IP) && options[:IP] == true)
            orig_ip = true
        end
    end
    
    if (!orig_ip)
        ip = NetAddr.unpack_ip_addr(@network, :Version => @version)
    else
        ip = NetAddr.unpack_ip_addr(@ip, :Version => @version)
    end
    ip = NetAddr.shorten(ip) if (short && @version == 6)
    mask = NetAddr.unpack_ip_netmask(@netmask)

    return("#{ip}/#{mask}")
end

#enumerate(options = nil) ⇒ Object

Synopsis

Provide all IP addresses contained within the IP space of this CIDR.

cidr4 = NetAddr::CIDR.create('192.168.1.1/24')
cidr6 = NetAddr::CIDR.create('fec0::/64')
puts "first 4 cidr4 addresses (bitstep 32)"
cidr4.enumerate(:Limit => 4, :Bitstep => 32).each {|x| puts "  #{x}"} 
puts "first 4 cidr6 addresses (bitstep 32)"
cidr6.enumerate(:Limit => 4, :Bitstep => 32, :Objectify => true).each {|x| puts "  #{x.desc}"}

Arguments:

  • Optional Hash with the following keys:

    :Bitstep -- enumerate in X sized steps - Integer (optional)
    :Limit -- limit returned list to X number of items - Integer (optional)
    :Objectify -- if true, return NetAddr::CIDR objects (optional)
    :Short -- if true, return IPv6 addresses in short-hand notation (optional)
    

Returns:

  • Array of Strings, or Array of NetAddr::CIDR objects



436
437
438
439
440
441
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
# File 'lib/cidr.rb', line 436

def enumerate(options=nil)
    known_args = [:Bitstep, :Limit, :Objectify, :Short]
    bitstep = 1
    objectify = false
    limit = nil
    short = false

    if (options)
        if (!options.kind_of? Hash)
            raise ArgumentError, "Expected Hash, but #{options.class} provided."
        end
        NetAddr.validate_args(options.keys,known_args)
        
        if( options.has_key?(:Bitstep) )
            bitstep = options[:Bitstep]
        end

        if( options.has_key?(:Objectify) && options[:Objectify] == true )
            objectify = true
        end

        if( options.has_key?(:Limit) )
            limit = options[:Limit]
        end
        
        if( options.has_key?(:Short) && options[: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.unpack_ip_addr(my_ip, :Version => @version)
            my_ip_s = NetAddr.shorten(my_ip_s) if (short && @version == 6)
            list.push( my_ip_s )
        else
            list.push( NetAddr::CIDR.create(my_ip, :Version => @version) )
        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

#eql?(cidr) ⇒ Boolean

Synopsis

Return true if the current CIDR and the provided CIDR are equal (base address and netmask are equal).

cidr4 = NetAddr::CIDR.create(‘192.168.1.0/24’) cidr4.eql?(‘192.168.1.0/24’)

Arguments:

  • CIDR address or NetAddr::CIDR object

Returns:

  • true or false

Returns:

  • (Boolean)


506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
# File 'lib/cidr.rb', line 506

def eql?(cidr)
    is_eql = 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
    
    is_eql = true if (self.packed_network == cidr.packed_network && self.packed_netmask == cidr.packed_netmask)
    
    return(is_eql)
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.

cidr4 = NetAddr::CIDR.create(‘192.168.1.0/24’) subnets = cidr4.fill_in()

Arguments:

  • Array of CIDR addresses, or Array of NetAddr::CIDR objects

  • Optional Hash with the following keys:

    :Objectify -- if true, return NetAddr::CIDR objects (optional)
    :Short -- if true, return IPv6 addresses in short-hand notation (optional)
    

Returns:

  • Array of CIDR Strings, or an Array of NetAddr::CIDR objects

Raises:

  • (ArgumentError)


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
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
# File 'lib/cidr.rb', line 549

def fill_in(list, options=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 (options)     
        raise ArgumentError, "Hash expected for argument 'options' but " +
                             "#{options.class} provided." if (!options.kind_of?(Hash) )
        NetAddr.validate_args(options.keys,known_args)

        if (options.has_key?(:Short) && options[:Short] == true)
            short = true
        end

        if (options.has_key?(:Objectify) && options[: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
    
    # sort our cidr's and see what is missing
    complete_list = []
    expected = self.packed_network
    NetAddr.sort(cidr_list).each do |cidr|
        network = cidr.packed_network
        bitstep = (@all_f + 1) - cidr.packed_netmask
        
        if (network > expected)
            num_ips_missing = network - expected
            sub_list = make_subnets_from_base_and_ip_count(expected,num_ips_missing)
            complete_list.concat(sub_list)                               
        elsif (network < expected)
            next
        end
        complete_list.push(NetAddr::CIDR.create(network,
                                                :PackedNetmask => cidr.packed_netmask,
                                                :Version => self.version))
        expected = network + bitstep
    end
    
    # if expected is not the next subnet, then we're missing subnets 
    # at the end of the cidr
    next_sub = self.next_subnet(:Objectify => true).packed_network
    if (expected != next_sub)
        num_ips_missing = next_sub - expected
        sub_list = make_subnets_from_base_and_ip_count(expected,num_ips_missing)
        complete_list.concat(sub_list)
    end
    
    # decide what to return
    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.

puts cidr4.ip() puts cidr4.ip(:Objectify => true).desc

Arguments:

  • Optional Hash with the following keys:

    :Objectify -- if true, return NetAddr::CIDR object (optional)
    :Short -- if true, return IPv6 addresses in short-hand notation (optional)
    

Returns:

  • String or NetAddr::CIDR object.



653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
# File 'lib/cidr.rb', line 653

def ip(options=nil)
    known_args = [:Objectify, :Short]
    objectify = false
    short = false
    
    if (options)
        if (!options.kind_of?(Hash))
            raise Argumenterror, "Expected Hash, but " +
                                 "#{options.class} provided."
        end
        NetAddr.validate_args(options.keys,known_args)
        
        if( options.has_key?(:Short) && options[:Short] == true )
            short = true
        end
        
        if( options.has_key?(:Objectify) && options[:Objectify] == true )
            objectify = true
        end
    end

    
    
    if (!objectify)
        ip = NetAddr.unpack_ip_addr(@ip, :Version => @version)
        ip = NetAddr.shorten(ip) if (short && @version == 6)
    else
        ip = NetAddr::CIDR.create(@ip, :Version => @version)
    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.

cidr4 = NetAddr::CIDR.create(‘192.168.1.1/24’) puts “#NetAddr::CIDR.cidr4cidr4.desc is contained within 192.168.0.0/23” if ( cidr4.is_contained?(‘192.168.0.0/23’) )

Arguments:

  • CIDR address or NetAddr::CIDR object

Returns:

  • true or false

Returns:

  • (Boolean)


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
# File 'lib/cidr.rb', line 703

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.packed_network 
    netmask = cidr.packed_netmask
    hostmask = cidr.packed_hostmask

    # if network == @network, then we have to go by netmask length
    # else we can tell by or'ing network and @network by hostmask
    # and comparing the results
    if (network == @network)
        is_contained = true if (@netmask > netmask)

    else
        if ( (network | hostmask) == (@network | hostmask) )
            is_contained = true
        end
    end

    return(is_contained)
end

#last(options = nil) ⇒ Object

Synopsis

Provide last IP address in this CIDR object.

puts cidr4.last()

Arguments:

  • Optional Hash with the following keys:

    :Objectify -- if true, return NetAddr::CIDR object (optional)
    :Short -- if true, return IPv6 addresses in short-hand notation (optional)
    

Returns:

  • String or NetAddr::CIDR object.



756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
# File 'lib/cidr.rb', line 756

def last(options=nil)
    known_args = [:Objectify, :Short]
    objectify = false
    short = false
    
    if (options)
        if (!options.kind_of?(Hash))
            raise Argumenterror, "Expected Hash, but " +
                                 "#{options.class} provided."
        end
        NetAddr.validate_args(options.keys,known_args)
        
        if( options.has_key?(:Short) && options[:Short] == true )
            short = true
        end
        
        if( options.has_key?(:Objectify) && options[:Objectify] == true )
            objectify = true
        end

    end
    
    packed_ip = @network | @hostmask
    if (!objectify)
        ip = NetAddr.unpack_ip_addr(packed_ip, :Version => @version)
        ip = NetAddr.shorten(ip) if (short && !objectify && @version == 6)
    else
        ip = NetAddr::CIDR.create(packed_ip, :Version => @version)
    end

    return(ip)
end

#matches?(ip) ⇒ Boolean

Synopsis

Given an IP address (or if a CIDR, then the original IP of that CIDR), determine if it falls within the range of addresses resulting from the combination of the IP and Wildcard Mask of this CIDR.

cidr4 = NetAddr.CIDRv4.new(‘10.0.0.0’, :WildcardMask => [‘0.7.0.255’, :inversed]) 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 address as a String or a CIDR object

Returns:

  • True or False

Returns:

  • (Boolean)


810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
# File 'lib/cidr.rb', line 810

def matches?(ip)
    packed = nil
    if (!ip.kind_of?(NetAddr::CIDR))
        begin
            packed = NetAddr.pack_ip_addr(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)
        packed = ip.packed_ip
    end

    mask = ~@wildcard_mask & @all_f

    return(true) if (@ip & mask == packed & 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.

mcast = NetAddr::CIDR.create(‘224.0.0.6’) puts mcast.multicast_mac.address

Arguments:

  • Optional Hash with the following keys:

    :Objectify -- if true, return EUI objects (optional)
    

Returns:

  • String or NetAddr::EUI48 object



848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
# File 'lib/cidr.rb', line 848

def multicast_mac(options=nil)
    known_args = [:Objectify]
    objectify = false
    
    if (options)
        if (!options.kind_of? Hash)
            raise ArgumentError, "Expected Hash, but #{options.class} provided."
        end
        NetAddr.validate_args(options.keys,known_args)
    
        if (options.has_key?(:Objectify) && options[: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

#netmaskObject

Synopsis

Provide netmask in CIDR format (/yy).

puts cidr4.netmask()

Arguments:

  • none

Returns:

  • String



902
903
904
905
# File 'lib/cidr.rb', line 902

def netmask()
    bits = NetAddr.unpack_ip_netmask(@netmask)
    return("/#{bits}")
end

#network(options = nil) ⇒ Object Also known as: base, first

Synopsis

Provide base network address.

puts cidr4.network()

Arguments:

  • Optional Hash with the following fields:

    :Objectify -- if true, return NetAddr::CIDR object (optional)
    :Short -- if true, return IPv6 addresses in short-hand notation (optional)
    

Returns:

  • String or NetAddr::CIDR object.



924
925
926
927
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
# File 'lib/cidr.rb', line 924

def network(options=nil)
    known_args = [:Objectify, :Short]
    objectify = false
    short = false
    
    if (options)
        if (!options.kind_of?(Hash))
            raise Argumenterror, "Expected Hash, but " +
                                 "#{options.class} provided."
        end
        NetAddr.validate_args(options.keys,known_args)
        
        if( options.has_key?(:Short) && options[:Short] == true )
            short = true
        end
        
        if( options.has_key?(:Objectify) && options[:Objectify] == true )
            objectify = true
        end
    end

        
    if (!objectify)
        ip = NetAddr.unpack_ip_addr(@network, :Version => @version)
        ip = NetAddr.shorten(ip) if (short && @version == 6)
    else
        ip = NetAddr::CIDR.create(@network, :Version => @version)
    end

    return(ip)
end

#next_ip(options = nil) ⇒ Object

Synopsis

Provide the next IP following the last available IP within this CIDR object.

cidr4 = NetAddr::CIDR.create(‘192.168.1.1/24’) cidr6 = NetAddr::CIDR.create(‘fec0::/64’) puts “cidr4 next subnet #NetAddr::CIDR.cidr4cidr4.next_subnet()” puts “cidr6 next subnet #=> true)”

Arguments:

  • Optional Hash with the following keys:

    :Bitstep -- step in X sized steps - Integer (optional)
    :Objectify -- if true, return NetAddr::CIDR object (optional)
    :Short -- if true, return IPv6 addresses in short-hand notation (optional)
    

Returns:

  • String or NetAddr::CIDR object.



980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
# File 'lib/cidr.rb', line 980

def next_ip(options=nil)
    known_args = [:Bitstep, :Objectify, :Short]
    bitstep = 1
    objectify = false
    short = false
    
    if (options)
        if (!options.kind_of?(Hash))
            raise Argumenterror, "Expected Hash, but " +
                                 "#{options.class} provided."
        end
        NetAddr.validate_args(options.keys,known_args)
        
        if( options.has_key?(:Bitstep) )
            bitstep = options[:Bitstep]
        end
        
        if( options.has_key?(:Short) && options[:Short] == true )
            short = true
        end
    
        if( options.has_key?(:Objectify) && options[: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.unpack_ip_addr(next_ip, :Version => @version)
        next_ip = NetAddr.shorten(next_ip) if (short && @version == 6)
    else
        next_ip = NetAddr::CIDR.create(next_ip, :Version => @version)
    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.

cidr4 = NetAddr::CIDR.create('192.168.1.1/24')
cidr6 = NetAddr::CIDR.create('fec0::/64')
puts "cidr4 next subnet #{cidr4.next_subnet()}"
puts "cidr6 next subnet #{cidr6.next_subnet(:Short => true)}"

Arguments:

  • Optional Hash with the following keys:

    :Bitstep -- step in X sized steps. - Integer (optional)
    :Objectify -- if true, return NetAddr::CIDR object (optional)
    :Short -- if true, return IPv6 addresses in short-hand notation (optional)
    

Returns:

  • String or NetAddr::CIDR object.



1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
# File 'lib/cidr.rb', line 1045

def next_subnet(options=nil)
    known_args = [:Bitstep, :Objectify, :Short]
    bitstep = 1
    objectify = false
    short = false
    
    if (options)
        if (!options.kind_of?(Hash))
            raise Argumenterror, "Expected Hash, but " +
                                 "#{options.class} provided."
        end
        NetAddr.validate_args(options.keys,known_args)
        
        if( options.has_key?(:Bitstep) )
            bitstep = options[:Bitstep]
        end
        
        if( options.has_key?(:Short) && options[:Short] == true )
            short = true
        end
    
        if( options.has_key?(:Objectify) && options[:Objectify] == true )
            objectify = true
        end
    end
    
    bitstep = bitstep * (2**(@max_bits - 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.unpack_ip_addr(next_sub, :Version => @version)
        next_sub = NetAddr.shorten(next_sub) if (short && @version == 6)        
        next_sub = next_sub << "/" << self.bits.to_s
    else
        next_sub = NetAddr::CIDR.create(next_sub, 
                                        :PackedNetmask => self.packed_netmask, 
                                        :Version => @version)
    end
    
    return(next_sub)
end

#nth(index, options = nil) ⇒ Object

Synopsis

Provide the nth IP within this object.

cidr4 = NetAddr::CIDR.create(‘192.168.1.1/24’) puts cidr4.nth(1) puts cidr4.nth(1, :Objectify => true

Arguments:

  • Index number as an Integer

  • Optional Hash with the following keys:

    :Objectify -- if true, return NetAddr::CIDR objects (optional)
    :Short -- if true, return IPv6 addresses in short-hand notation (optional)
    

Returns:

  • String or NetAddr::CIDR object.

Raises:

  • (ArgumentError)


1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
# File 'lib/cidr.rb', line 1111

def nth(index, options=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 (options)     
        raise ArgumentError, "Hash expected for argument 'options' but #{options.class} provided." if (!options.kind_of?(Hash) )
        NetAddr.validate_args(options.keys,known_args)

        if( options.has_key?(:Short) && options[:Short] == true )
            short = true
        end
    
        if( options.has_key?(:Objectify) && options[:Objectify] == true )
                objectify = true
        end
    end
    
    my_ip = @network + index
    if ( (@hostmask | my_ip) == (@hostmask | @network) )
        
        if (!objectify)
            my_ip = NetAddr.unpack_ip_addr(my_ip, :Version => @version)
            my_ip = NetAddr.shorten(my_ip) if (short && @version == 6)
        else
            my_ip = NetAddr::CIDR.create(my_ip, :Version => @version)
        end

    else
        raise BoundaryError, "Index of #{index} returns IP that is out of " +
                             "bounds of CIDR network."
    end

    return(my_ip)
end

#packed_hostmaskObject

Synopsis

Provide an Integer representation of the Hostmask of this object.

puts cidr4.packed_hostmask().to_s(16)

Arguments:

  • none

Returns:

  • Integer



1167
1168
1169
# File 'lib/cidr.rb', line 1167

def packed_hostmask()
    return(@hostmask)
end

#packed_ipObject

Synopsis

Provide an Integer representation of the IP address of this object.

puts cidr4.packed_ip().to_s(16)

Arguments:

  • none

Returns:

  • Integer



1186
1187
1188
# File 'lib/cidr.rb', line 1186

def packed_ip()
    return(@ip)
end

#packed_netmaskObject

Synopsis

Provide an Integer representation of the Netmask of this object.

puts cidr4.packed_netmask().to_s(16)

Arguments:

  • none

Returns:

  • Integer



1205
1206
1207
# File 'lib/cidr.rb', line 1205

def packed_netmask()
    return(@netmask)
end

#packed_networkObject

Synopsis

Provide an Integer representation of the Network address of this object.

packed = cidr4.packed_network().to_s(16)

Arguments:

  • none

Returns:

  • Integer



1224
1225
1226
# File 'lib/cidr.rb', line 1224

def packed_network()
    return(@network)
end

#packed_wildcard_maskObject

Synopsis

Provide an Integer representation of the IPv4 Wildcard Mask.

puts cidr4.packed_wildcard_mask()

Arguments:

  • none

Returns:

  • Integer



1243
1244
1245
# File 'lib/cidr.rb', line 1243

def packed_wildcard_mask()
    return(@wildcard_mask)
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.

cidr4 = NetAddr::CIDR.create(‘192.168.1.1/24’) list = cidr4.range(0, 1) list = cidr4.range(0, 1, :Objectify => true) list = cidr4.range(0, nil, :Objectify => true)

Arguments:

  • Lower range boundary index as an Integer

  • Upper range boundary index as an Integer

  • Optional Hash with the following keys:

    :Bitstep -- enumerate in X sized steps - Integer (optional)
    :Objectify -- if true, return NetAddr::CIDR objects (optional)
    :Short -- if true, return IPv6 addresses in short-hand notation (optional)
    

Returns:

  • Array of Strings, or Array of NetAddr::CIDR objects

Raises:

  • (ArgumentError)


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
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
# File 'lib/cidr.rb', line 1272

def range(lower, upper=nil, options=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 (options)     
        raise ArgumentError, "Hash expected for argument 'options' but #{options.class} provided." if (!options.kind_of?(Hash) )
        NetAddr.validate_args(options.keys,known_args)
        
        if( options.has_key?(:Short) && options[:Short] == true )
            short = true
        end
    
        if( options.has_key?(:Objectify) && options[:Objectify] == true )
            objectify = true
        end
    
        if( options.has_key?(:Bitstep) )
            bitstep = options[: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.unpack_ip_addr(my_ip, :Version => @version)
            ip = NetAddr.shorten(ip) if (short && @version == 6)
        else
            ip = NetAddr::CIDR.create(:PackedIP => my_ip, :Version => @version)
        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.remainder(‘192.168.1.32/27’).each {|x| puts x} cidr4.remainder(‘192.168.1.32/27’, :Objectify => true).each {|x| puts x.desc}

Arguments:

  • CIDR address or NetAddr::CIDR object

  • Optional Hash with the following keys:

    :Objectify -- if true, return NetAddr::CIDR objects (optional)
    :Short -- if true, return IPv6 addresses in short-hand notation (optional)
    

Returns:

  • Array of Strings, or Array of NetAddr::CIDR objects



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
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
# File 'lib/cidr.rb', line 1356

def remainder(addr, options=nil)
    known_args = [:Objectify, :Short]
    short = nil
    objectify = nil
    
    # validate options
    if (options)     
        raise ArgumentError, "Hash expected for argument 'options' but " +
                             "#{options.class} provided." if (!options.kind_of?(Hash) )
        NetAddr.validate_args(options.keys,known_args)
        
        if( options.has_key?(:Short) && options[:Short] == true )
            short = true
        end
    
        if( options.has_key?(:Objectify) && options[: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.packed_network
    upper_network = self.packed_network + 2**(@max_bits - new_mask)
    
    new_subnets = []
    until(new_mask > addr.bits)
        if (addr.packed_network < upper_network)
            match = lower_network
            non_match = upper_network
        else
            match = upper_network
            non_match = lower_network
        end

        
        if (!objectify)
            non_match = NetAddr.unpack_ip_addr(non_match, :Version => @version)
            non_match = NetAddr.shorten(non_match) if (short && @version == 6)
            new_subnets.unshift("#{non_match}/#{new_mask}")
        else
            new_subnets.unshift(NetAddr::CIDR.create(non_match, 
                                                     :PackedNetmask => NetAddr.pack_ip_netmask(new_mask), 
                                                     :Version => @version))
        end
        
        new_mask = new_mask + 1
        lower_network = match
        upper_network = match + 2**(@max_bits - 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.

cidr4 = NetAddr::CIDR.create(‘192.168.1.1/24’) new_cidr = cidr4.resize(23) puts new_cidr.desc

Arguments:

  • Netmask as an Integer

Returns:

  • NetAddr::CIDR object

Raises:

  • (Argumenterror)


1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
# File 'lib/cidr.rb', line 1452

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.pack_ip_netmask(bits, :Version => @version)
    network = @network & netmask
    
    cidr = NetAddr::CIDR.create(network, :PackedNetmask => netmask, :Version => @version)
    return(cidr)
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.

cidr4 = NetAddr::CIDR.create(‘192.168.1.1/24’) new_cidr = cidr4.resize(23) puts new_cidr.desc

Arguments:

  • Netmask as an Integer

Returns:

  • True

Raises:

  • (Argumenterror)


1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
# File 'lib/cidr.rb', line 1483

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.pack_ip_netmask(bits, :Version => @version)
    
    @netmask = netmask
    @network = @network & netmask
    @hostmask = @netmask ^ @all_f
    
    # check @ip
    if ((@ip & @netmask) != (@network))
        @ip = @network
    end
    
    return(true)
end

#sizeObject

Synopsis

Provide number of IP addresses within this CIDR.

puts cidr4.size()

Arguments:

  • none

Returns:

  • Integer



1517
1518
1519
# File 'lib/cidr.rb', line 1517

def size()
    return(@hostmask + 1)
end

#subnet(options = nil) ⇒ Object

Synopsis

Subnet this CIDR. There are 2 ways to subnet:

* By providing the netmask (in bits) of the new subnets in :Bits.
* By providing the number of IP addresses needed in the new subnets in :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.

cidr_list = cidr4.subnet(:Bits => 28, :NumSubnets => 3).each {|x| puts “ #{x}”} cidr_list = cidr4.subnet(:IPCount => 19).each {|x| puts “ #{x}”} cidr4.subnet(:Bits => 28).each {|x| puts “ #{x}”} “ cidr6.subnet(:Bits => 67, :NumSubnets => 4, :Short => true).each {|x| puts ” #{x}“}

Arguments:

  • Optional Hash with the following keys:

    :Bits --  Netmask (in bits) of new subnets - Integer (optional)
    :IPCount -- Minimum number of IP's that new subnets should contain - Integer (optional)
    :NumSubnets -- Number of X sized subnets to return - Integer (optional)
    :Objectify -- if true, return NetAddr::CIDR objects (optional)
    :Short -- if true, return IPv6 addresses in short-hand notation (optional)
    

Returns:

  • Array of Strings, or Array of NetAddr::CIDR objects



1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
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
# File 'lib/cidr.rb', line 1560

def subnet(options=nil)
    known_args = [:Bits, :IPCount, :NumSubnets, :Objectify, :Short]
    my_network = self.packed_network
    my_mask = self.bits
    subnet_bits = my_mask + 1
    min_count = nil 
    objectify = false
    short = false       
    
    if (options)
        if (!options.kind_of? Hash)
            raise ArgumentError, "Expected Hash, but #{options.class} provided."
        end
        NetAddr.validate_args(options.keys,known_args)
        
        if ( options.has_key?(:IPCount) )
            subnet_bits = NetAddr.minimum_size(options[:IPCount], :Version => @version)
        end
        
        if ( options.has_key?(:Bits) )
            subnet_bits = options[:Bits]
        end
        
        if ( options.has_key?(:NumSubnets) )
            num_subnets = options[:NumSubnets]
        end
        
        if( options.has_key?(:Short) && options[:Short] == true )
            short = true
        end
    
        if( options.has_key?(:Objectify) && options[: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 > @max_bits)
        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**(@max_bits - subnet_bits)
    subnets = self.enumerate(:Bitstep => bitstep, :Limit => num_subnets)

    # save our subnets
    new_subnets = []
    subnets.each do |subnet|
        if (!objectify)
            subnet = NetAddr.shorten(subnet) if (short && @version == 6)
            new_subnets.push("#{subnet}/#{subnet_bits}")
        else            
            new_subnets.push(NetAddr::CIDR.create("#{subnet}/#{subnet_bits}", :Version => @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.unpack_ip_addr(next_supernet_ip, :Version => @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.create(next_supernet_ip,
                                                  :PackedNetmask => NetAddr.pack_ip_netmask(next_supernet_bits),
                                                  :Version => @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

#wildcard_mask(mask = nil, inversed = nil) ⇒ Object

Synopsis

Set or return the wildcard mask. Wildcard masks are typically used for matching entries in an access-list.

cidr4.wildcard_mask() -> reads the current wildcard mask cidr4.wildcard_mask(‘0.0.0.255’, :inversed) -> sets wildcard mask using a reversed mask cidr4.wildcard_mask(‘255.255.255.0’) -> sets wildcard mask using a standard mask

Arguments:

  • wildcard mask as a String or Integer

  • the label :inversed if the mask is bit-flipped. (optional)

Returns:

  • nil



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
# File 'lib/cidr.rb', line 1688

def wildcard_mask(mask=nil, inversed=nil)
    if (mask)
        if (mask.kind_of?(Integer)) 
            packed = mask
        else
            packed = nil
            begin
                packed = NetAddr.pack_ip_addr(mask, :Version => @version)
            rescue NetAddr::ValidationError
                raise NetAddr::ValidationError, "Wildcard Mask must be a valid IPv#{@version} address."
            end
        end
        packed = packed ^ @all_f if (inversed != :inversed)
        @wildcard_mask = packed
        ret_val = nil
    else
        if (inversed != :inversed)
            ret_val = NetAddr.unpack_ip_addr(@wildcard_mask ^ @all_f, :Version => @version)
        else
            ret_val = NetAddr.unpack_ip_addr(@wildcard_mask, :Version => @version)
        end
    end

    return(ret_val)
end