Class: IPAdmin::CIDR

Inherits:
Object
  • Object
show all
Defined in:
lib/cidr.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ CIDR

  • Arguments:

    • Hash with the following fields:

      - :CIDR -- IP address in CIDR notation - String (optional)
      - :Netmask -- IP Netmask - String or Integer (optional)
      - :PackedIP -- Integer representation of an IP address (optional)
      - :PackedNetmask -- Integer representation of an IP Netmask (optional)
      - :Version -- IP version - Integer (optional)
      - :Tag -- Custom descriptor tag - Hash, tag => value. (optional)
      
  • Notes:

    • At a minimum, either :CIDR or PackedIP must be provided.

    • Netmask defaults to /32 or /128 if not provided.

    • :PackedIP takes precedence over :CIDR

    • :PackedNetmask always takes precedence over any other provided netmasks.

    • Netmask within :CIDR takes precedence over :Netmask.

    • Version will be auto-detected if not specified

Example:

cidr4 = IPAdmin::CIDR.new(:CIDR => '192.168.1.1/24')
cidr4_2 = IPAdmin::CIDR.new(:PackedIP => 0x0a010001,
                            :PackedNetmask => 0xffffff00
                            :Version => 4)
cidr6 = IPAdmin::CIDR.new(:CIDR => 'fec0::/64',
                          :Tag => {'interface' => 'g0/1'})
cidr6_2 = IPAdmin::CIDR.new(:CIDR => '::ffff:192.168.1.1/96')


78
79
80
81
82
83
84
85
86
87
88
89
90
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
# File 'lib/cidr.rb', line 78

def initialize(options)
    if (!options.kind_of? Hash)
        raise ArgumentError, "Expected Hash, but #{options.class} provided."
    end


    if (options.has_key?(:PackedIP))
        packed_ip = options[:PackedIP]
        raise ArgumentError, "Expected Integer, but #{packed_ip.class} " +
                             "provided for option :PackedIP." if (!packed_ip.kind_of?(Integer))
    elsif (options.has_key?(:CIDR))
        cidr =  options[:CIDR]
        raise ArgumentError, "Expected String, but #{cidr.class} " +
                             "provided for option :CIDR." if (!cidr.kind_of?(String))      
    else
        raise ArgumentError, "Missing argument: CIDR or PackedIP."
    end        
    
    
    if (options.has_key?(:PackedNetmask))
        packed_netmask = options[:PackedNetmask]
        raise ArgumentError, "Expected Integer, but #{packed_netmask.class} " +
                             "provided for option :PackedNetmask." if (!packed_netmask.kind_of?(Integer))

    elsif (options.has_key?(:Netmask))
        netmask = options[:Netmask]
        raise ArgumentError, "Expected String or Integer, but #{netmask.class} " +
                             "provided for option :Netmask." if (!netmask.kind_of?(String) && !netmask.kind_of?(Integer))
    end      
    
    
    if (options.has_key?(:Version))
        @version = options[:Version]
        if (@version != 4 && @version != 6)
            raise ArgumentError, ":Version should be 4 or 6, but was '#{version}'."
        end
    end
    
    if (options.has_key?(:Tag))
        @tag = options[:Tag]
        if (!@tag.kind_of? Hash)
            raise ArgumentError, "Expected Hash, but #{@tag.class} provided for option :Tag."
        end
    end
    
    
    if (packed_ip)
        if (packed_ip < 2**32)
            @version = 4 if (!@version)
            @netmask = 2**32-1 if (!netmask && !packed_netmask)
        else
            @version = 6 if (!@version)
            @netmask = 2**128-1 if (!netmask && !packed_netmask)
        end
        
        # validate & store packed_ip
        IPAdmin.validate_ip_addr(:IP => packed_ip, :Version => @version)
        @ip = packed_ip
    
    else            
        # determine version if not set
        if (!@version)
            if (cidr =~ /\./ && cidr !~ /:/)
                @version = 4
            elsif (cidr =~ /:/)
                @version = 6
            end
        end        

        # get ip/netmask
        if (cidr =~ /\//) # if netmask part of cidr
            ip,netmask = cidr.split(/\//)
            raise ArgumentError, ":CIDR is improperly formatted." if (!ip || !netmask)
        elsif (@version == 4)
            ip = cidr
            @netmask = 2**32-1 if (!netmask && !packed_netmask)
        elsif (@version == 6)
            ip = cidr
            @netmask = 2**128-1 if (!netmask && !packed_netmask)
        end

        # validate & pack ip
        IPAdmin.validate_ip_addr(:IP => ip, :Version => @version)                
        @ip = IPAdmin.pack_ip_addr(:IP => ip, :Version => @version)            
        
    end

            
    # validate & store netmask || packed_netmask if needed
    if (!@netmask)
        if (packed_netmask)
            IPAdmin.validate_ip_netmask(:Netmask => packed_netmask, :Packed => true, :Version => @version)
            @netmask = packed_netmask
        else
            IPAdmin.validate_ip_netmask(:Netmask => netmask, :Version => @version)
            @netmask = IPAdmin.pack_ip_netmask(:Netmask => netmask, :Version => @version)
        end
    end
    
    # set vars based on version
    if (@version == 4)
        @max_bits = 32
        @all_f = 2**@max_bits - 1
    else
        @max_bits = 128
        @all_f = 2**@max_bits - 1
    end
    
    # get @network & @hostmask
    @network = (@ip & @netmask)
    @hostmask = @netmask ^ @all_f

end

Instance Attribute Details

#tagObject

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



28
29
30
# File 'lib/cidr.rb', line 28

def tag
  @tag
end

#versionObject (readonly)

IP version 4 or 6.



25
26
27
# File 'lib/cidr.rb', line 25

def version
  @version
end

Instance Method Details

#arpaObject

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.

  • Arguments:

    • none

  • Returns:

    • String

Example:

arpa = cidr4.arpa() --> '1.168.192.in-addr.arpa.'


214
215
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
246
247
248
249
250
251
252
253
254
# File 'lib/cidr.rb', line 214

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

Provide number of bits in Netmask.

  • Arguments:

    • none

  • Returns:

    • Integer.

Example:

puts cidr4.bits()   --> 24


276
277
278
# File 'lib/cidr.rb', line 276

def bits()
    return(IPAdmin.unpack_ip_netmask(:Integer => @netmask))
end

#contains?(object) ⇒ Boolean

Determines if this CIDR contains (is supernet of) the provided CIDR object.

  • Arguments:

    • CIDR object

  • Returns:

    • true or false

Example:

cidr4_2 = IPAdmin::CIDR.new(:CIDR => '192.168.1.0/26')
contains? = cidr4.contains(cidr4_2)   --> true


302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
# File 'lib/cidr.rb', line 302

def contains?(object)
    is_contained = false

    if (object.kind_of?(IPAdmin::CIDR))
        network = object.packed_network 
        netmask = object.packed_netmask

    else 
        raise ArgumentError, "Expected IPAdmin::CIDR " +
                             " object but #{object.class} provided."
    end


    if (object.version != @version)
        raise ArgumentError, "Attempted to compare a version #{object.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)
        is_contained = true if (netmask > @netmask)

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

    return(is_contained)
end

#desc(options = nil) ⇒ Object

Returns network/netmask in CIDR format.

  • Arguments:

    • Optional hash with the following fields:

      - :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

Example:

puts cidr4.desc()   --> 192.168.1.0/24
puts cidr4.desc(:IP => true)   --> 192.168.1.1/24


358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
# File 'lib/cidr.rb', line 358

def desc(options=nil)
    short = false
    orig_ip = false

    if (options)
        if (!options.kind_of? Hash)
            raise ArgumentError, "Expected Hash, but #{options.class} provided."
        end
        
        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 = IPAdmin.unpack_ip_addr(:Integer => @network, :Version => @version)
    else
        ip = IPAdmin.unpack_ip_addr(:Integer => @ip, :Version => @version)
    end
    ip = IPAdmin.shorten(ip) if (short && @version == 6)
    mask = IPAdmin.unpack_ip_netmask(:Integer => @netmask)

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

#enumerate(options = nil) ⇒ Object

Provide all IP addresses contained within the IP space of this CIDR. (warning: this can be quite large for big blocks)

  • Arguments:

    • Optional Hash with the following fields:

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

    • Array of Strings or CIDR objects

Example:

ip_list = cidr4.enumerate(:Bitstep => 2, :Limit => 2)   --> ['192.168.1.0','192.168.1.1']


412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
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
# File 'lib/cidr.rb', line 412

def enumerate(options=nil)
    bitstep = 1
    objectify = false
    limit = nil
    short = false

    if (options)
        if (!options.kind_of? Hash)
            raise ArgumentError, "Expected Hash, but #{options.class} provided."
        end
        
        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 = IPAdmin.unpack_ip_addr(:Integer => my_ip, :Version => @version)
            my_ip_s = IPAdmin.shorten(my_ip_s) if (short && @version == 6)
            list.push( my_ip_s )
        else
            list.push( IPAdmin::CIDR.new(:PackedIP => 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

#hostmask_extObject

Provide IPv4 Hostmask in extended format (y.y.y.y).

  • Arguments:

    • none

  • Returns:

    • String

Example:

puts cidr4.hostmask_ext()   --> 0.0.0.255


483
484
485
486
487
488
489
490
491
# File 'lib/cidr.rb', line 483

def hostmask_ext()
    if (@version == 4)
        hostmask = IPAdmin.unpack_ip_addr(:Integer => @hostmask, :Version => @version)
    else
        raise "IPv6 does not support extended hostmask notation." 
    end

    return(hostmask)
end

#ip(options = nil) ⇒ Object

Provide original IP address passed during initialization.

  • Arguments:

    • Optional Hash with the following fields:

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

    • String or CIDR object.

Example:

puts cidr4.ip()   --> 192.168.1.1


515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
# File 'lib/cidr.rb', line 515

def ip(options=nil)
    objectify = false
    short = false
    
    if (options)
        if (!options.kind_of?(Hash))
            raise Argumenterror, "Expected Hash, but " +
                                 "#{options.class} provided."
        end
        
        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 = IPAdmin.unpack_ip_addr(:Integer => @ip, :Version => @version)
        ip = IPAdmin.shorten(ip) if (short && @version == 6)
    else
        ip = IPAdmin::CIDR.new(:PackedIP => @ip, :Version => @version)
    end

    return(ip)
end

#last(options = nil) ⇒ Object Also known as: broadcast

Provide last IP address in this CIDR object.

  • Arguments:

    • Optional Hash with the following fields:

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

    • String or CIDR object.

  • Notes:

    • The broadcast() method is aliased to this method, and thus works for IPv6 despite the fact that the IPv6 protocol does not support IP broadcasting.

Example:

puts cidr4.last()   --> 192.168.1.255


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

def last(options=nil)
    objectify = false
    short = false
    
    if (options)
        if (!options.kind_of?(Hash))
            raise Argumenterror, "Expected Hash, but " +
                                 "#{options.class} provided."
        end
        
        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 = IPAdmin.unpack_ip_addr(:Integer => packed_ip, :Version => @version)
        ip = IPAdmin.shorten(ip) if (short && !objectify && @version == 6)
    else
        ip = IPAdmin::CIDR.new(:PackedIP => packed_ip, :Version => @version)
    end

    return(ip)
end

#multicast_mac(options = nil) ⇒ Object

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.

  • Arguments:

    • Optional hash with the following fields:

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

    • EUI object

  • Note:

    • MAC address is based on original IP address passed during initialization.

Example:

mcast = IPAdmin::CIDR.new(:CIDR => '224.0.0.6')
puts mcast.multicast_mac.address --> 01-00-5e-00-00-06


632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
# File 'lib/cidr.rb', line 632

def multicast_mac(options=nil)
    objectify = false
    
    if (options)
        if (!options.kind_of? Hash)
            raise ArgumentError, "Expected Hash, but #{options.class} provided."
        end
    
        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 "#{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 "#{self.ip} is not a valid multicast address. IPv6 multicast " +
                  "addresses should be in the range ff00::/8."
        end             
    end
    
    eui = IPAdmin::EUI.new(:PackedEUI => mac)
    eui = eui.address if (!objectify)

    return(eui)
end

#netmaskObject

Provide netmask in CIDR format.

  • Arguments:

    • none

  • Returns:

    • String

Example:

puts cidr4.netmask()   --> /24


689
690
691
692
# File 'lib/cidr.rb', line 689

def netmask()
    bits = IPAdmin.unpack_ip_netmask(:Integer => @netmask)
    return("/#{bits}")
end

#netmask_extObject

Provide IPv4 netmask in extended format (y.y.y.y).

  • Arguments:

    • none

  • Returns:

    • String

Example:

puts cidr4.netmask_ext()   --> 255.255.255.0


714
715
716
717
718
719
720
721
722
723
# File 'lib/cidr.rb', line 714

def netmask_ext()    
    if (@version == 4)
        netmask = IPAdmin.unpack_ip_addr(:Integer => @netmask)
    else
        raise "IPv6 does not support extended netmask notation. " +
              "Use netmask() method instead."
    end

    return(netmask)
end

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

Provide base network address.

  • Arguments:

    • Optional Hash with the following fields:

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

    • String or CIDR object.

Example:

puts cidr4.network()   --> 192.168.1.0


747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
# File 'lib/cidr.rb', line 747

def network(options=nil)
    objectify = false
    short = false
    
    if (options)
        if (!options.kind_of?(Hash))
            raise Argumenterror, "Expected Hash, but " +
                                 "#{options.class} provided."
        end
        
        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 = IPAdmin.unpack_ip_addr(:Integer => @network, :Version => @version)
        ip = IPAdmin.shorten(ip) if (short && @version == 6)
    else
        ip = IPAdmin::CIDR.new(:PackedIP => @network, :Version => @version)
    end

    return(ip)
end

#next_ip(options = nil) ⇒ Object

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

  • Arguments:

    • Optional Hash with the following fields:

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

    • String or CIDR object.

Example:

puts cidr4.next_ip()   --> 192.168.2.0


804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
# File 'lib/cidr.rb', line 804

def next_ip(options=nil)
    bitstep = 1
    objectify = false
    short = false
    
    if (options)
        if (!options.kind_of?(Hash))
            raise Argumenterror, "Expected Hash, but " +
                                 "#{options.class} provided."
        end
        
        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 "Returned IP is out of bounds for IPv#{@version}."
    end

            
    if (!objectify)
        next_ip = IPAdmin.unpack_ip_addr(:Integer => next_ip, :Version => @version)
        next_ip = IPAdmin.shorten(next_ip) if (short && @version == 6)
    else
        next_ip = IPAdmin::CIDR.new(:PackedIP => next_ip, :Version => @version)
    end
    
    return(next_ip)
end

#next_subnet(options = nil) ⇒ Object

Provide the next subnet following this CIDR object. The next subnet will be of the same size as the current CIDR object.

  • Arguments:

    • Optional Hash with the following fields:

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

    • String or CIDR object.

Example:

puts cidr4.next_subnet()   --> 192.168.2.0/24


869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
# File 'lib/cidr.rb', line 869

def next_subnet(options=nil)
    bitstep = 1
    objectify = false
    short = false
    
    if (options)
        if (!options.kind_of?(Hash))
            raise Argumenterror, "Expected Hash, but " +
                                 "#{options.class} provided."
        end
        
        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 "Returned subnet is out of bounds for IPv#{@version}."
    end

    netmask =  self.bits       
    if (!objectify)
        next_sub = IPAdmin.unpack_ip_addr(:Integer => next_sub, :Version => @version)
        next_sub = IPAdmin.shorten(next_sub) if (short && @version == 6)        
        next_sub = next_sub << "/" << netmask.to_s
    else
        next_sub = IPAdmin::CIDR.new(:PackedIP => next_sub, :Netmask => netmask, :Version => @version)
    end
    
    return(next_sub)
end

#nth(options) ⇒ Object

Provide the nth IP within this object.

  • Arguments:

    • Hash with the following fields:

      - :Index -- index number of the IP address to return - Integer
      - :Objectify -- if true, return IPAdmin::CIDR objects (optional)
      - :Short -- if true, return IPv6 addresses in short-hand notation (optional)
      
  • Returns:

    • String or CIDR object.

Example:

puts cidr4.nth(:Index => 1)   --> 192.168.1.1


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
960
961
962
963
964
965
966
967
968
969
970
971
972
973
# File 'lib/cidr.rb', line 935

def nth(options)
    objectify = false
    short = false

    if (!options.kind_of?(Hash))
        raise ArgumentError, "Expected Hash, but " +
                             "#{options.class} provided."
    end
    
    if ( !options.has_key?(:Index) )
        raise ArgumentError, "Missing argument: Index."
    end
    index = options[:Index]

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

    my_ip = @network + index
    if ( (@hostmask | my_ip) == (@hostmask | @network) )
        
        if (!objectify)
            my_ip = IPAdmin.unpack_ip_addr(:Integer => my_ip, :Version => @version)
            my_ip = IPAdmin.shorten(my_ip) if (short && @version == 6)
        else
            my_ip = IPAdmin::CIDR.new(:PackedIP => my_ip, :Version => @version)
        end

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

    return(my_ip)
end

#packed_hostmaskObject

Provide an integer representation of the Hostmask of this object.

  • Arguments:

    • none

  • Returns:

    • Integer

Example:

puts cidr4.packed_hostmask().to_s(16)   --> 0xff


995
996
997
# File 'lib/cidr.rb', line 995

def packed_hostmask()
    return(@hostmask)
end

#packed_ipObject

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

  • Arguments:

    • none

  • Returns:

    • Integer

Example:

puts cidr4.packed_ip().to_s(16)   --> 0xc0c80101


1019
1020
1021
# File 'lib/cidr.rb', line 1019

def packed_ip()
    return(@ip)
end

#packed_netmaskObject

Provide an integer representation of the Netmask of this object.

  • Arguments:

    • none

  • Returns:

    • Integer

Example:

puts cidr4.packed_netmask().to_s(16)   --> 0xffffff00


1043
1044
1045
# File 'lib/cidr.rb', line 1043

def packed_netmask()
    return(@netmask)
end

#packed_networkObject

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

  • Arguments:

    • none

  • Returns:

    • Integer

Example:

packed = cidr4.packed_network().to_s(16)   --> 0xc0c80100


1067
1068
1069
# File 'lib/cidr.rb', line 1067

def packed_network()
    return(@network)
end

#range(options) ⇒ Object

Given two Indexes, return all IP addresses within the CIDR that are between them (inclusive).

  • Arguments:

    • Hash with the following fields:

      - :Bitstep -- enumerate in X sized steps - Integer (optional)
      - :Indexes -- index numbers of the addresses to use as boundaries - Array of (2) Integers
      - :Objectify -- if true, return IPAdmin::CIDR objects (optional)
      - :Short -- if true, return IPv6 addresses in short-hand notation (optional)
      
  • Returns:

    • Array Strings or CIDR objects

Example:

list = cidr4.range(:Indexes => [0,1]) --> ['192.168.1.0','192.168.1.1']


1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
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
1151
1152
# File 'lib/cidr.rb', line 1096

def range(options)
    objectify = false
    short = false
    bitstep = 1

    if (!options.kind_of?(Hash))
        raise Argumenterror, "Expected Hash, but #{options.class} provided."
    end
    
    if ( !options.has_key?(:Indexes) )
        raise ArgumentError, "Missing argument: Indexes."
    end
    indexes = options[:Indexes]
    indexes.sort!
    
    if( (!indexes.kind_of?(Array)) || (indexes.length != 2))
        raise ArgumentError, "Argument :Index should be an array of (2) index numbers."
    end

    if ( (indexes[0] < 0) || (indexes[0] > self.size) )
        raise ArgumentError, "Index #{indexes[0]} is out of bounds for this CIDR."
    end
    
    if (indexes[1] >= self.size)
        raise ArgumentError, "Index #{indexes[1]} is out of bounds for this CIDR."
    end
    
    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

    start_ip = @network + indexes[0]
    end_ip = @network + indexes[1]
    my_ip = start_ip
    list = []
    until (my_ip > end_ip)            
        if (!objectify)
            ip = IPAdmin.unpack_ip_addr(:Integer => my_ip, :Version => @version)
            ip = IPAdmin.shorten(ip) if (short && @version == 6)
        else
            ip = IPAdmin::CIDR.new(:PackedIP => my_ip, :Version => @version)
        end
        
        list.push(ip)
        my_ip += bitstep
    end

    return(list)
end

#remainder(options) ⇒ Object

Given a portion of the current CIDR, provide the remainder of the CIDR. 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 remainder.

  • Arguments:

    • Optional hash with the following fields:

      - :Exclude -- CIDR object to use in calculating the remainder.
      - :Objectify -- if true, return IPAdmin::CIDR objects (optional)
      - :Short -- if true, return IPv6 addresses in short-hand notation (optional)
      
  • Returns:

    • Array of Strings or CIDR objects

Example:

cidr4_2 = IPAdmin::CIDR.new(:CIDR => '192.168.1.64/26')
cidr4.remainder(:Exclude => cidr4_2).each {|x| puts}


1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
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
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
# File 'lib/cidr.rb', line 1182

def remainder(options)
    short = nil
    objectify = nil
    
    if (!options.kind_of? Hash)
        raise ArgumentError, "Expected Hash, but #{options.class} provided."
    end
        
    if ( !options.has_key?(:Exclude) )
        raise ArgumentError, "Missing argument: Exclude."
    end
    to_exclude = options[:Exclude]
        
    if ( !to_exclude.kind_of?(IPAdmin::CIDR) )
        raise ArgumentError, "Expeced IPAdmin::CIDR, but #{exclude.class} " +
                             "for option: Exclude."
    end
    
    if( options.has_key?(:Short) && options[:Short] == true )
        short = true
    end
    
    if( options.has_key?(:Objectify) && options[:Objectify] == true )
        objectify = true
    end
    
    # make sure 'to_exclude' is the same ip version
    if ( to_exclude.version != @version )
        raise "#{to_exclude.desc(:Short => true)} is of a different " +
              "IP version than #{self.desc(:Short => true)}."
    end    

    # make sure we contain 'to_exclude'
    if ( self.contains?(to_exclude) != true )
        raise "#{to_exclude.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 off 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 > to_exclude.bits)
        if (to_exclude.packed_network < upper_network)
            match = lower_network
            non_match = upper_network
        else
            match = upper_network
            non_match = lower_network
        end

        
        if (!objectify)
            non_match = IPAdmin.unpack_ip_addr(:Integer => non_match, :Version => @version)
            non_match = IPAdmin.shorten(non_match) if (short && @version == 6)
            new_subnets.unshift("#{non_match}/#{new_mask}")
        else
            new_subnets.unshift(IPAdmin::CIDR.new(:PackedIP => non_match, 
                                                  :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(options) ⇒ Object

Resize the CIDR by changing the size of the Netmask. Return the resulting CIDR as a new object.

  • Arguments:

    • Hash with the following fields:

      - :Subnet -- Number of bits of new Netmask - Integer
      
  • Returns:

    • CIDR object

Example:

new_cidr = cidr4.resize(:Subnet => 23)
puts new_cidr.desc   --> 192.168.1.0/23


1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
# File 'lib/cidr.rb', line 1279

def resize(options)
    if (!options.kind_of?(Hash))
            raise Argumenterror, "Expected Hash, but " +
                                 "#{options.class} provided."
    end
        
    if ( !options.has_key?(:Subnet) )
            raise Argumenterror, "Missing argument: Subnet."
    end
    bits = options[:Subnet]
    
    IPAdmin.validate_ip_netmask(:Netmask => bits, :Version => @version)
    netmask = IPAdmin.pack_ip_netmask(:Netmask => bits, :Version => @version)
    network = @network & netmask
    
    cidr = IPAdmin::CIDR.new(:PackedIP => network, :PackedNetmask => netmask, :Version => @version)
    return(cidr)
end

#resize!(options) ⇒ Object

Resize this object by changing the size of the Netmask.

  • Arguments:

    • Hash with the following fields:

      - :Subnet -- Number of bits of new Netmask - Integer
      
  • Returns:

    • nil

  • Notes:

    • If CIDR is resized such that the original IP is no longer contained within, then that IP will be reset to the base network address.

Example:

cidr4.resize!(:Subnet => 23)
puts cidr4.desc   --> 192.168.1.0/23


1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
# File 'lib/cidr.rb', line 1324

def resize!(options)
    if (!options.kind_of?(Hash))
            raise Argumenterror, "Expected Hash, but " +
                                 "#{options.class} provided."
    end
        
    if ( !options.has_key?(:Subnet) )
            raise Argumenterror, "Missing argument: Subnet."
    end
    bits = options[:Subnet]
    
    IPAdmin.validate_ip_netmask(:Netmask => bits, :Version => @version)
    netmask = IPAdmin.pack_ip_netmask(:Netmask => bits, :Version => @version)
    
    @netmask = netmask
    @network = @network & netmask
    @hostmask = @netmask ^ @all_f
    
    # check @ip
    if ((@ip & @netmask) != (@network))
        @ip = @network
    end
    
    return(nil)
end

#sizeObject

Provide number of IP addresses within this object.

  • Arguments:

    • none

  • Returns:

    • Integer

Example:

puts cidr4.size()   --> 256


1370
1371
1372
# File 'lib/cidr.rb', line 1370

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

#subnet(options = nil) ⇒ Object

Subnet this object. Object will be fully subnetted into X number of subnets of specified size. If :MinCount is provided, then method will return at least that number of subnets (of size X) and the remainder of the new subnets will be merged together as tightly as possible. If a size is not provided, then the current CIDR will be split in half.

  • Arguments:

    • Optional hash with the following fields:

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

    • Array of CIDR addresses or IPAdmin::CIDR objects

  • Notes:

    • :Subnet always takes precedence over :IPCount.

Example:

cidr_list = cidr4.subnet(:Subnet => 28, :MinCount => 3)
cidr_list = cidr4.subnet(:IPCount => 19)
puts cidr_list[0]   --> 192.168.1.0/27


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
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
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
# File 'lib/cidr.rb', line 1408

def subnet(options=nil)
    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
        
        if ( options.has_key?(:IPCount) )
            subnet_bits = IPAdmin.minimum_size(:IPCount => options[:IPCount],
                                               :Version => @version)
        end
        
        if ( options.has_key?(:Subnet) )
            subnet_bits = options[:Subnet]
        end
        
        if ( options.has_key?(:MinCount) )
            min_count = options[:MinCount]
        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 min_count is a power of 2
    bits_needed = 1
    min_count = num_avail if (!min_count)
    until (2**bits_needed >= min_count)
        bits_needed += 1
    end
    min_count = 2**bits_needed
    next_supernet_bits = subnet_bits - bits_needed
    

    # make sure subnet isnt bigger than available bits
    if (subnet_bits > @max_bits)
        raise "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 "Requested subnet (#{subnet_bits}) is too large for " +
              "current CIDR space."
    end

    # make sure MinCount is smaller than available subnets
    if (min_count > num_avail)
        raise "Requested subnet count (#{min_count}) exceeds subnets " +
              "available for allocation (#{num_avail})."
    end

    # list all 'subnet_bits' sized subnets of this cidr block
    # with a limit of min_count
    bitstep = 2**(@max_bits - subnet_bits)
    subnets = self.enumerate(:Bitstep => bitstep, :Limit => min_count)

    # save our subnets
    new_subnets = []
    subnets.each do |subnet|
        if (!objectify)
            subnet = IPAdmin.shorten(subnet) if (short && @version == 6)
            new_subnets.push("#{subnet}/#{subnet_bits}")
        else            
            new_subnets.push(IPAdmin::CIDR.new(:CIDR => "#{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 * min_count)
    next_supernet_ip = my_network + next_supernet_bitstep
    until (next_supernet_bits == my_mask)
        if (!objectify)
            next_network = IPAdmin.unpack_ip_addr(:Integer => next_supernet_ip, :Version => @version)
            next_network = IPAdmin.shorten(next_network) if (short && @version == 6)
            new_subnets.push("#{next_network}/#{next_supernet_bits}")
        else
            new_subnets.push(IPAdmin::CIDR.new(:PackedIP => next_supernet_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