Module: NetAddr

Defined in:
lib/eui.rb,
lib/cidr.rb,
lib/tree.rb,
lib/methods.rb,
lib/net_addr.rb

Overview

Copyleft © 2006 Dustin Spinhirne (www.spinhirne.com)

Licensed under the same terms as Ruby, No Warranty is provided.

Defined Under Namespace

Classes: BoundaryError, CIDR, CIDRv4, CIDRv6, EUI, EUI48, EUI64, NetStruct, Tree, ValidationError, VersionError

Class Method Summary collapse

Class Method Details

.merge(list, options = nil) ⇒ Object

Synopsis

Given a list of CIDR addresses or NetAddr::CIDR objects of the same version, merge (summarize) them in the most efficient way possible. Summarization will only occur when the newly created supernets will not result in the ‘creation’ of new IP space. For example the following blocks (192.168.0.0/24, 192.168.1.0/24, and 192.168.2.0/24) would be summarized into 192.168.0.0/23 and 192.168.2.0/24 rather than into 192.168.0.0/22

I have designed this with enough flexibility so that you can pass in CIDR addresses that arent even related (ex. 192.168.1.0/26, 192.168.1.64/27, 192.168.1.96/27 10.1.0.0/26, 10.1.0.64/26) and they will be merged properly (ie 192.168.1.0/25, and 10.1.0.0/25 would be returned).

Example: supernets = NetAddr.merge() supernets = NetAddr.merge() supernets = NetAddr.merge(, :Short => true)

Arguments:

  • Array of CIDR addresses as Strings, or an 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 addresses as Strings, or an Array of NetAddr::CIDR objects

Raises:

  • (ArgumentError)


40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
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
# File 'lib/methods.rb', line 40

def merge(list,options=nil)
    known_args = [:Objectify, :Short]
    version = nil
    all_f = nil
    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?(:Objectify) && options[:Objectify] == true)
            objectify = true
        end
        
        if (options.has_key?(:Short) && options[:Short] == true)
            short = true 
        end
    end
    
    # make sure all are valid types of the same IP version
    supernet_list = []
    list.each do |obj|
        if (!obj.kind_of?(NetAddr::CIDR))
            begin
                obj = NetAddr::CIDR.create(obj)
            rescue Exception => error
                raise ArgumentError, "An array element of :List raised the following " +
                                     "errors: #{error}"
            end
        end

        version = obj.version if (!version)
        all_f = obj.all_f if (!all_f)
        if (!obj.version == version)
            raise VersionError, "Provided objects must be of the same IP version."
        end 
        supernet_list.push(obj)
    end

    # merge subnets by removing them from 'supernet_list',
    # and categorizing them into hash of arrays ({packed_netmask => [packed_network,packed_network,etc...] ) 
    # within each categorization we merge contiguous subnets
    # and then remove them from that category & put them back into
    # 'supernet_list'. we do this until supernet_list stops getting any shorter
    categories = {}
    supernet_list_length = 0
    until (supernet_list_length == supernet_list.length)
        supernet_list_length = supernet_list.length

        # categorize
        supernet_list.each do |cidr|
            netmask = cidr.packed_netmask
            network = cidr.packed_network
            if (categories.has_key?(netmask) )
                categories[netmask].push(network)
            else
                categories[netmask] = [network]
            end
        end
        supernet_list.clear

        ordered_cats = categories.keys.sort        
        ordered_cats.each do |netmask|
            nets = categories[netmask].sort
            bitstep = (all_f + 1) - netmask
            
            until (nets.length == 0)
                # take the first network & create its supernet. this
                # supernet will have x number of subnets, so we'll look
                # & see if we have those subnets. if so, keep supernet & delete subnets.
                to_merge = []
                multiplier = 1
                network1 = nets[0]
                num_required = 2**multiplier
                supermask = (netmask << multiplier) & all_f
                supernet = supermask & network1
                if (network1 == supernet)
                    # we have the first half of the new supernet                   
                    expected = network1
                    nets.each do |network|
                        if (network == expected)
                            to_merge.push(network)
                            expected = expected + bitstep
                            if ( (to_merge.length == num_required) && (nets.length > num_required) )
                                # we have all of our subnets for this round, but still have
                                # more to look at
                                multiplier += 1
                                num_required = 2**multiplier
                                supermask = (netmask << multiplier) & all_f
                                supernet = supermask & network1
                            end
                        else
                            break 
                        end
                    end
                else
                   # we have the second half of the new supernet only
                   to_merge.push(network1)
                end

                
                if (to_merge.length != num_required)
                    # we dont have all of our subnets, so backstep 1 bit                    
                    multiplier -= 1
                    supermask = (netmask << multiplier) & all_f
                    supernet = supermask & network1
                end
                
                # save new supernet
                supernet_list.push(NetAddr::CIDR.create(supernet,
                                                        :PackedNetmask => supermask,
                                                        :Version => version))
                
                # delete the subnets of the new supernet
                (2**multiplier).times {nets.delete(to_merge.shift)}               
            end
        end
        categories.clear
        supernet_list = NetAddr.sort(supernet_list)
    end

    # decide what to return
    if (!objectify)
            supernets = []
            supernet_list.each {|entry| supernets.push(entry.desc(:Short => short))}
            return(supernets)
    else
            return(supernet_list)
    end

end

.minimum_size(ipcount, options = nil) ⇒ Object

Synopsis

Given the number of IP addresses required in a subnet, return the minimum netmask (bits by default) required for that subnet. IP version is assumed to be 4 unless specified otherwise.

Example: netmask = NetAddr.minumum_size(14) netmask = NetAddr.minumum_size(65536, :Version => 6)

Arguments:

  • IP count as an Integer

  • Optional Hash with the following keys:

    :Extended -- If true, then return the netmask in extended format (y.y.y.y) for IPv4
    :Version -- IP version - Integer(optional)
    

Returns:

  • Integer or String

Raises:

  • (ArgumentError)


199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
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
# File 'lib/methods.rb', line 199

def minimum_size(ipcount, options=nil)
    version = 4
    extended = false
    known_args = [:Version, :Extended]

    # validate ipcount
    raise ArgumentError, "Integer expected for argument 'ipcount' but #{ipcount.class} provided." if (!ipcount.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?(:Version))
            version = options[:Version]
        end
        
        if (options.has_key?(:Extended) && options[:Extended] == true)
            extended = true
        end
    end
    
    if (version == 4)
        max_bits = 32
    else
        max_bits = 128
    end
    
    
    if (ipcount > 2**max_bits) 
        raise BoundaryError, "Required IP count exceeds number of IP addresses available " +
                             "for IPv#{version}."
    end

    
    bits_needed = 0
    until (2**bits_needed >= ipcount)
        bits_needed += 1
    end
    subnet_bits = max_bits - bits_needed
    
    return(NetAddr.unpack_ip_addr(NetAddr.pack_ip_netmask(subnet_bits))) if (extended && version == 4)
    return(subnet_bits)
end

.pack_ip_addr(ip, options = nil) ⇒ Object

Synopsis

Convert IP addresses into an Integer. Will attempt to auto-detect IP version if not provided.

Example: pack_ip_addr(‘192.168.1.1’) pack_ip_addr(ffff::1’, :Version => 6) pack_ip_addr(::192.168.1.1’)

Arguments:

  • IP address as a String

  • Optional Hash with the following keys:

    :Version -- IP version - Integer
    

Returns:

  • Integer



266
267
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
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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
# File 'lib/methods.rb', line 266

def pack_ip_addr(ip, options=nil)
    known_args = [:Version]
    to_validate = {}
    
    # 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]
            to_validate[:Version] = version
            if (version != 4 && version != 6)
                raise  VersionError, ":Version should be 4 or 6, but was '#{version}'."
            end
        end
    end 
    
    if ( ip.kind_of?(String) )
        
        # validate
        NetAddr.validate_ip_addr(ip, to_validate)
        
        # determine version if not provided
        if (!version)
            if ( ip =~ /\./ && ip !~ /:/ )
                version = 4
            else
                version = 6
            end
        end
        
        packed_ip = 0
        if ( version == 4)
            octets = ip.split('.')            
            (0..3).each do |x|
                octet = octets.pop.to_i
                octet = octet << 8*x 
                packed_ip = packed_ip | octet
            end
            
        else
            # if ipv4-mapped ipv6 addr
            if (ip =~ /\./)
                dotted_dec = true                 
            end            
            
            # split up by ':'
            fields = []
            if (ip =~ /::/)
                shrthnd = ip.split( /::/ )
                if (shrthnd.length == 0)
                    return(0) 
                else                    
                    first_half = shrthnd[0].split( /:/ ) if (shrthnd[0])
                    sec_half = shrthnd[1].split( /:/ ) if (shrthnd[1])
                    first_half = [] if (!first_half)
                    sec_half = [] if (!sec_half)
                end
                missing_fields = 8 - first_half.length - sec_half.length
                missing_fields -= 1 if dotted_dec
                fields = fields.concat(first_half)
                missing_fields.times {fields.push('0')}
                fields = fields.concat(sec_half)               
                
            else
               fields = ip.split(':')  
            end
           
            if (dotted_dec)
                ipv4_addr = fields.pop
                packed_v4 = NetAddr.pack_ip_addr(ipv4_addr, :Version => 4)
                octets = []
                2.times do
                    octet = packed_v4 & 0xFFFF
                    octets.unshift(octet.to_s(16))
                    packed_v4 = packed_v4 >> 16
                end
                fields.concat(octets)
            end

            # pack
            (0..7).each do |x|
                field = fields.pop.to_i(16)
                field = field << 16*x 
                packed_ip = packed_ip | field
            end
            
        end

    else
        raise ArgumentError, "String expected for argument 'ip' but #{ip.class} provided."    
    end

    return(packed_ip)
end

.pack_ip_netmask(netmask, options = nil) ⇒ Object

Synopsis

Convert IP netmask into an Integer. Netmask may be in either CIDR (/yy) or extended (y.y.y.y) format. CIDR formatted netmasks may either be a String or an Integer. IP version defaults to 4. It may be necessary to specify the version if an IPv6 netmask of /32 or smaller is provided.

Example: packed = NetAddr.pack_ip_netmask(‘255.255.255.0’) packed = NetAddr.pack_ip_netmask(‘24’) packed = NetAddr.pack_ip_netmask(24) packed = NetAddr.pack_ip_netmask(‘/24’) packed = NetAddr.pack_ip_netmask(‘32’, :Version => 6)

Arguments

  • Netmask as a String or Integer

  • Optional Hash with the following keys:

    :Version -- IP version - Integer (optional)
    

Returns:

  • Integer



389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
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
# File 'lib/methods.rb', line 389

def pack_ip_netmask(netmask, options=nil)
    known_args = [:Version]
    all_f = 2**32-1
    to_validate = {}
    
    # 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]
            if (version != 4 && version != 6)
                raise VersionError, ":Version should be 4 or 6, but was '#{version}'."
            elsif (version == 6)
                all_f = 2**128-1
            else
                all_f = 2**32-1
            end
            to_validate[:Version] = version
        end
    end
    
    if (netmask.kind_of?(String))
        NetAddr.validate_ip_netmask(netmask, to_validate)
        
        if(netmask =~ /\./)
            packed_netmask = NetAddr.pack_ip_addr(netmask)

        else
            # remove '/' if present
            if (netmask =~ /^\// )
                netmask[0] = " "
                netmask.lstrip!
            end
            netmask = netmask.to_i
            packed_netmask = all_f ^ (all_f >> netmask)
        end
        
    elsif (netmask.kind_of?(Integer))
        to_validate[:Packed] = true
        NetAddr.validate_ip_netmask(netmask, to_validate)
        packed_netmask = all_f ^ (all_f >> netmask)
    
    else
        raise ArgumentError, "String or Integer expected for argument 'netmask', " +
                             "but #{netmask.class} provided." if (!netmask.kind_of?(Integer) && !netmask.kind_of?(String))    
    end
    
    return(packed_netmask)
end

.range(cidr1, cidr2, options = nil) ⇒ Object

Synopsis

Given two CIDR addresses or NetAddr::CIDR objects of the same version, return all IP addresses between them. NetAddr.range will use the original IP address passed during the initialization of the NetAddr::CIDR objects, or the ip address of any CIDR addresses passed. The default behavior is to be non-inclusive (don’t include boundaries as part of returned data)

Example: list = NetAddr.range(cidr1,cidr2, :Limit => 10) list = NetAddr.range(‘192.168.1.0’,‘192.168.1.10’, :Inclusive => true)

Arguments:

  • Lower boundary CIDR as a String or NetAddr::CIDR object

  • Upper boundary CIDR as a String or NetAddr::CIDR object

  • Optional Hash with the following keys:

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

Returns:

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



470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
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
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
# File 'lib/methods.rb', line 470

def range(cidr1, cidr2, options=nil)
    known_args = [:Bitstep, :Inclusive, :Limit, :Objectify, :Short]
    list = []
    bitstep = 1
    objectify = false
    short = false
    inclusive = false
    limit = nil

    # if cidr1/cidr2 are not CIDR objects, then attempt to create
    # cidr objects from them
    if ( !cidr1.kind_of?(NetAddr::CIDR) )
        begin
            cidr1 = NetAddr::CIDR.create(cidr1)
        rescue Exception => error
            raise ArgumentError, "Argument 'cidr1' raised the following " +
                                 "errors: #{error}"
        end
    end
    
    if ( !cidr2.kind_of?(NetAddr::CIDR))
        begin
            cidr2 = NetAddr::CIDR.create(cidr2)
        rescue Exception => error
            raise ArgumentError, "Argument 'cidr2' raised the following " +
                                 "errors: #{error}"
        end
    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?(:Bitstep) )
            bitstep = options[:Bitstep]
        end

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

        if( options.has_key?(:Limit) )
            limit = options[:Limit]
        end
    end

    # check version, store & sort
    if (cidr1.version == cidr2.version)
        version = cidr1.version
        boundaries = [cidr1.packed_ip, cidr2.packed_ip]
        boundaries.sort
    else
        raise VersionError, "Provided NetAddr::CIDR objects are of different IP versions."
    end

    # dump our range
    if (!inclusive)
        my_ip = boundaries[0] + 1
        end_ip = boundaries[1]
    else
        my_ip = boundaries[0]
        end_ip = boundaries[1] + 1
    end
    
    until (my_ip >= end_ip) 
        if (!objectify)
            my_ip_s = NetAddr.unpack_ip_addr(my_ip, :Version => version)
            my_ips = NetAddr.shorten(my_ips) 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
        if (limit)
            limit = limit -1
            break if (limit == 0)
        end
    end

    return(list)
end

.shorten(addr) ⇒ Object

Synopsis

Take a standard IPv6 address, and format it in short-hand notation. The address should not contain a netmask.

Example: short = NetAddr.shorten(‘fec0:0000:0000:0000:0000:0000:0000:0001’)

Arguments:

  • String

Returns:

  • String



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
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
# File 'lib/methods.rb', line 580

def shorten(addr)

    # is this a string?
    if (!addr.kind_of? String)
        raise ArgumentError, "Expected String, but #{addr.class} provided."
    end

    validate_ip_addr(addr, :Version => 6)

    # make sure this isnt already shorthand
    if (addr =~ /::/)
        return(addr)
    end

    # split into fields
    fields = addr.split(":")
    
    # check last field for ipv4-mapped addr
    if (fields.last() =~ /\./ )
        ipv4_mapped = fields.pop()
    end
    
    # look for most consecutive '0' fields
    start_field,end_field = nil,nil
    start_end = []
    consecutive,longest = 0,0
        
    (0..(fields.length-1)).each do |x|
        fields[x] = fields[x].to_i(16)

        if (fields[x] == 0)
            if (!start_field)
                start_field = x
                end_field = x
            else
                end_field = x
            end
            consecutive += 1
        else
            if (start_field)
                if (consecutive > longest)
                    longest = consecutive
                    start_end = [start_field,end_field]
                    start_field,end_field = nil,nil                    
                end
                consecutive = 0
            end
        end

        fields[x] = fields[x].to_s(16)
    end
    
    # if our longest set of 0's is at the end, then start & end fields
    # are already set. if not, then make start & end fields the ones we've
    # stored away in start_end
    if (consecutive > longest) 
        longest = consecutive
    else
        start_field = start_end[0]
        end_field = start_end[1]
    end

    if (longest > 1)        
        fields[start_field] = ''
        start_field += 1
        fields.slice!(start_field..end_field)
    end 
    fields.push(ipv4_mapped) if (ipv4_mapped)   
    short = fields.join(':')    
    short << ':' if (short =~ /:$/)
    
    return(short)
end

.sort(list) ⇒ Object

Synopsis

Given a list of CIDR addresses or NetAddr::CIDR objects, sort them from lowest to highest by Network/Netmask. NetAddr.sort will use the base address passed during the initialization of any NetAddr::CIDR objects, or the base address of any CIDR addresses passed

Example: sorted = NetAddr.sort() sorted = NetAddr.sort()

Arguments:

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

Returns:

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



675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
# File 'lib/methods.rb', line 675

def sort(list)

    # make sure list is an array
    if ( !list.kind_of?(Array) )
        raise ArgumentError, "Array of NetAddr::CIDR or NetStruct " +
                             "objects expected, but #{list.class} provided."
    end

    # make sure all are valid types of the same IP version
    version = nil
    cidr_hash = {}
    list.each do |cidr|
        if (!cidr.kind_of?(NetAddr::CIDR))
            begin
                new_cidr = NetAddr::CIDR.create(cidr)
            rescue Exception => error
                raise ArgumentError, "An element of the provided Array " +
                                     "raised the following errors: #{error}"
            end
        else
            new_cidr = cidr
        end
        cidr_hash[new_cidr] = cidr
        
        version = new_cidr.version if (!version)
        unless (new_cidr.version == version)
            raise VersionError, "Provided CIDR addresses must all be of the same IP version."
        end 
    end

    # sort by network. if networks are equal, sort by netmask.
    sorted_list = []
    cidr_hash.each_key do |entry|
        index = 0
        sorted_list.each do
            if(entry.packed_network < (sorted_list[index]).packed_network)
                break
            elsif (entry.packed_network == (sorted_list[index]).packed_network)
                if (entry.packed_netmask < (sorted_list[index]).packed_netmask)
                    break
                end
            end
            index += 1
        end
        sorted_list.insert(index, entry)
    end
    
    # return original values passed
    ret_list = []
    sorted_list.each {|x| ret_list.push(cidr_hash[x])}

    return(ret_list)
end

.unpack_ip_addr(packed_ip, options = nil) ⇒ Object

Synopsis

Unack a packed IP address back into a printable string. Will attempt to auto-detect IP version if not provided.

Example: unpacked = NetAddr.unpack_ip_addr(3232235906) unpacked = NetAddr.unpack_ip_addr(packed, :Version => 6)

Arguments:

  • Packed IP address as an Integer

  • Optional Hash with the following keys:

    :Version -- IP version - Integer (optional)
    :IPv4Mapped -- if true, unpack IPv6 as an IPv4 mapped address (optional)
    

Returns:

  • String

Raises:

  • (ArgumentError)


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
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
# File 'lib/methods.rb', line 751

def unpack_ip_addr(packed_ip, options=nil)
    known_args = [:Version, :IPv4Mapped]
    ipv4_mapped = false
    to_validate = {}
    
    # 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]
            to_validate[:Version] = version
            if (version != 4 && version != 6)
                raise VersionError, ":Version should be 4 or 6, but was '#{version}'."
            end
        end
    
        if (options.has_key?(:IPv4Mapped) && options[:IPv4Mapped] == true)
            ipv4_mapped = true
        end
    end
    
    # validate
    raise ArgumentError, "Integer expected for argument 'packed_ip', " +
                         "but #{packed_ip.class} provided." if (!packed_ip.kind_of?(Integer))
    NetAddr.validate_ip_addr(packed_ip, to_validate)
    
    # set version if not set
    if (!version)
        if (packed_ip < 2**32)
            version = 4
        else
            version = 6
        end
    end
    
    if (version == 4)
        octets = []
        4.times do
            octet = packed_ip & 0xFF
            octets.unshift(octet.to_s)
            packed_ip = packed_ip >> 8
        end
        ip = octets.join('.')
    else
        fields = []
        if (!ipv4_mapped)
            loop_count = 8
        else
            loop_count = 6
            packed_v4 = packed_ip & 0xffffffff
            ipv4_addr = NetAddr.unpack_ip_addr(packed_v4, :Version => 4)
            fields.unshift(ipv4_addr)
            packed_ip = packed_ip >> 32
        end
        
        loop_count.times do 
            octet = packed_ip & 0xFFFF
            octet = octet.to_s(16)
            packed_ip = packed_ip >> 16

            # if octet < 4 characters, then pad with 0's
            (4 - octet.length).times do
                octet = '0' << octet
            end
            fields.unshift(octet)
        end        
        ip = fields.join(':')
    end
    

    return(ip)
end

.unpack_ip_netmask(packed_netmask) ⇒ Object

Synopsis

Unpack a packed IP netmask into an Integer representing the number of bits in the CIDR mask.

Example: unpacked = NetAddr.unpack_ip_netmask(0xfffffffe)

Arguments:

  • Packed netmask as an Integer

Returns:

  • Integer

Raises:

  • (ArgumentError)


844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
# File 'lib/methods.rb', line 844

def unpack_ip_netmask(packed_netmask)
    
    # validate packed_netmask
    raise ArgumentError, "Integer expected for argument 'packed_netmask', " +
                         "but #{packed_netmask.class} provided." if (!packed_netmask.kind_of?(Integer))    
    
    if (packed_netmask < 2**32)
        mask = 32
        NetAddr.validate_ip_netmask(packed_netmask, :Packed => true, :Version => 4)
    else
        NetAddr.validate_ip_netmask(packed_netmask, :Packed => true, :Version => 6)
        mask = 128
    end
    
    
    mask.times do    
        if ( (packed_netmask & 1) == 1)
            break
        end
        packed_netmask = packed_netmask >> 1
        mask = mask - 1
    end

    return(mask)
end

.unshorten(ip) ⇒ Object

Synopsis

Take an IPv6 address in short-hand format, and expand it into standard notation. The address should not contain a netmask.

Example: long = NetAddr.unshorten(‘fec0::1’)

Arguments:

  • CIDR address as a String

Returns:

  • String



888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
# File 'lib/methods.rb', line 888

def unshorten(ip)

    # is this a string?
    if (!ip.kind_of? String)
        raise ArgumentError, "Expected String, but #{ip.class} provided."
    end

    validate_ip_addr(ip, :Version => 6)
    ipv4_mapped = true if (ip =~ /\./)
    
    packed = pack_ip_addr(ip, :Version => 6)    
    if (!ipv4_mapped)
        long = unpack_ip_addr(packed, :Version => 6)
    else
        long = unpack_ip_addr(packed, :Version => 6, :IPv4Mapped => true)
    end
    
    return(long)
end

.validate_args(to_validate, known_args) ⇒ Object

validate options hash



1350
1351
1352
1353
1354
1355
# File 'lib/methods.rb', line 1350

def validate_args(to_validate,known_args)
    to_validate.each do |x|
        raise ArgumentError, "Unrecognized argument #{x}. Valid arguments are " +
                             "#{known_args.join(',')}" if (!known_args.include?(x))
    end
end

.validate_eui(eui) ⇒ Object

Synopsis

Validate an EUI-48 or EUI-64 address. Raises NetAddr::ValidationError on validation failure.

Example: NetAddr.validate_eui(‘01-00-5e-12-34-56’)

  • Arguments

  • EUI address as a String

Returns:

  • True



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
955
956
957
958
959
# File 'lib/methods.rb', line 925

def validate_eui(eui)
    if (eui.kind_of?(String))
        # check for invalid characters
        if (eui =~ /[^0-9a-fA-f\.\-\:]/)
            raise ValidationError, "#{eui} is invalid (contains invalid characters)."
        end
            
        # split on formatting characters & check lengths
        if (eui =~ /\-/)
            fields = eui.split('-')
            if (fields.length != 6 && fields.length != 8)
                raise ValidationError, "#{eui} is invalid (unrecognized formatting)."
            end
            fields.each {|x| raise ValidationError, "#{eui} is invalid (missing characters)." if (x.length != 2)} 
        elsif (eui =~ /\:/)
            fields = eui.split(':')
            if (fields.length != 6 && fields.length != 8)
                raise ValidationError, "#{eui} is invalid (unrecognized formatting)."
            end
            fields.each {|x| raise ValidationError, "#{eui} is invalid (missing characters)." if (x.length != 2)}
        elsif (eui =~ /\./)
            fields = eui.split('.')
            if (fields.length != 3 && fields.length != 4)
                raise ValidationError, "#{eui} is invalid (unrecognized formatting)."
            end
            fields.each {|x| raise ValidationError, "#{eui} is invalid (missing characters)." if (x.length != 4)}
        else
            raise ValidationError, "#{eui} is invalid (unrecognized formatting)."
        end

    else
        raise ArgumentError, "EUI address should be a String, but was a#{eui.class}."
    end
    return(true)
end

.validate_ip_addr(ip, options = nil) ⇒ Object

Synopsis

Validate an IP address. The address should not contain a netmask. IP version will attempt to be auto-detected if not provided. Raises NetAddr::ValidationError on validation failure.

Example: NetAddr.validate_ip_addr(‘192.168.1.1’) NetAddr.validate_ip_addr(‘ffff::1’, :Version => 6) NetAddr.validate_ip_addr(‘::192.168.1.1’) NetAddr.validate_ip_addr(0xFFFFFF) NetAddr.validate_ip_addr(2**128-1) NetAddr.validate_ip_addr(2**32-1, :Version => 4)

Arguments

  • IP address as a String or Integer

  • Optional Hash with the following keys:

    :Version -- IP version - Integer (optional)
    

Returns:

  • True



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
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
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
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
# File 'lib/methods.rb', line 987

def validate_ip_addr(ip, options=nil)
    known_args = [:Version]
    
    # 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]
            if (version != 4 && version != 6)
                raise ArgumentError, ":Version should be 4 or 6, but was '#{version}'."
            end
        end
    end
    
    if ( ip.kind_of?(String) )
        
        # check validity of charaters
        if (ip =~ /[^0-9a-fA-F\.:]/)
            raise ValidationError, "#{ip} is invalid (contains invalid characters)."
        end
        
        # determine version if not specified
        if (!version && (ip =~ /\./ && ip !~ /:/ ) )
            version = 4
        elsif (!version && ip =~ /:/)
            version = 6
        end        
        
        if (version == 4)
            octets = ip.split('.')            
            raise ValidationError, "#{ip} is invalid (IPv4 requires (4) octets)." if (octets.length != 4)
            
            # are octets in range 0..255?
            octets.each do |octet|
                raise ValidationError, "#{ip} is invalid (IPv4 dotted-decimal format " +
                                       "should not contain non-numeric characters)." if (octet =~ /[^0-9]/ )                
                octet = octet.to_i()                
                if ( (octet < 0) || (octet >= 256) )
                    raise ValidationError, "#{ip} is invalid (IPv4 octets should be between 0 and 255)."
                end
            end        
        
        elsif (version == 6)
            # make sure we only have at most (2) colons in a row, and then only
            # (1) instance of that
            if ( (ip =~ /:{3,}/) || (ip.split("::").length > 2) )
                raise ValidationError, "#{ip} is invalid (IPv6 field separators (:) are bad)."
            end            
            
            # set flags
            shorthand = false
            if (ip =~ /\./)
                dotted_dec = true 
            else
                dotted_dec = false
            end            
            
            # split up by ':'
            fields = []
            if (ip =~ /::/)
                shorthand = true
                ip.split('::').each do |x|
                    fields.concat( x.split(':') )
                end
            else
               fields.concat( ip.split(':') ) 
            end
            
            # make sure we have the correct number of fields
            if (shorthand)
                if ( (dotted_dec && fields.length > 6) || (!dotted_dec && fields.length > 7) )
                    raise ValidationError, "#{ip} is invalid (IPv6 shorthand notation has " +
                                           "incorrect number of fields)." 
                end                
            else
                if ( (dotted_dec && fields.length != 7 ) || (!dotted_dec && fields.length != 8) )
                    raise ValidationError, "#{ip} is invalid (IPv6 address has " +
                                           "incorrect number of fields)." 
                end
            end
            
            # if dotted_dec then validate the last field
            if (dotted_dec)
                dotted = fields.pop()
                octets = dotted.split('.')
                raise ValidationError, "#{ip} is invalid (Legacy IPv4 portion of IPv6 " +
                                       "address should contain (4) octets)." if (octets.length != 4)
                octets.each do |x|
                    raise ValidationError, "#{ip} is invalid (egacy IPv4 portion of IPv6 " +
                                           "address should not contain non-numeric characters)." if (x =~ /[^0-9]/ )
                    x = x.to_i
                    if ( (x < 0) || (x >= 256) )
                        raise ValidationError, "#{ip} is invalid (Octets of a legacy IPv4 portion of IPv6 " +
                                               "address should be between 0 and 255)."
                    end
                end
            end
            
            # validate hex fields
            fields.each do |x|
                if (x =~ /[^0-9a-fA-F]/)
                    raise ValidationError, "#{ip} is invalid (IPv6 address contains invalid hex characters)."
                else
                    x = x.to_i(16)
                    if ( (x < 0) || (x >= 2**16) )
                        raise ValidationError, "#{ip} is invalid (Fields of an IPv6 address " +
                                               "should be between 0x0 and 0xFFFF)."
                    end
                end
            end
            
        else
            raise ValidationError, "#{ip} is invalid (Did you mean to pass an Integer instead of a String?)."        
        end

    elsif ( ip.kind_of?(Integer) )
        if (version && version == 4)
            raise ValidationError, "#{ip} is invalid for IPv4 (Integer is out of bounds)." if ( (ip < 0) || (ip > 2**32-1) )
        else
            raise ValidationError, "#{ip} is invalid for IPv6 (Integer is out of bounds)." if ( (ip < 0) || (ip > 2**128-1) )
        end
        
    else
        raise ArgumentError, "Integer or String expected for argument 'ip' but " +
                             "#{ip.class} provided." if (!ip.kind_of?(String) && !ip.kind_of?(Integer))
    end

    
    return(true)
end

.validate_ip_netmask(netmask, options = nil) ⇒ Object

Synopsis

Validate IP Netmask.Version defaults to 4 if not specified. Raises NetAddr::ValidationError on validation failure.

Examples: NetAddr.validate_ip_netmask(‘/32’) NetAddr.validate_ip_netmask(32) NetAddr.validate_ip_netmask(0xffffffff, :Packed => true)

Arguments:

  • Netmask as a String or Integer

  • Optional Hash with the following keys:

    :Packed -- if true, the provided Netmask is a packed Integer
    :Version -- IP version - Integer (optional)
    

Returns:

  • True



1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
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
# File 'lib/methods.rb', line 1143

def validate_ip_netmask(netmask, options=nil)
    known_args = [:Packed, :Version]
    packed = false
    version = 4
    max_bits = 32
    
    # 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?(:Packed) && options[:Packed] == true)
            packed = true
        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}'."
            elsif (version == 6)
                max_bits = 128
            else
                max_bits = 32
            end
        end    
    end
    
    if (netmask.kind_of?(String))
        if(netmask =~ /\./)
            all_f = 2**32-1
            packed_netmask = 0
        
            # validate & pack extended mask
            begin
                validate_ip_addr(netmask)
                packed_netmask = pack_ip_addr(netmask)
            rescue Exception
                raise ValidationError, "#{netmask} is an improperly formed IPv4 address."
            end

            # cycle through the bits of hostmask and compare
            # with packed_mask. when we hit the firt '1' within
            # packed_mask (our netmask boundary), xor hostmask and
            # packed_mask. the result should be all 1's. this whole
            # process is in place to make sure that we dont have
            # and crazy masks such as 255.254.255.0
            hostmask = 1
            32.times do 
                check = packed_netmask & hostmask
                if ( check != 0)
                    hostmask = hostmask >> 1
                    unless ( (packed_netmask ^ hostmask) == all_f)
                        raise ValidationError, "#{netmask} contains '1' bits within the host portion of the netmask." 
                    end
                    break
                else
                    hostmask = hostmask << 1
                    hostmask = hostmask | 1
                end
            end

        else
            # remove '/' if present
            if (netmask =~ /^\// )
                netmask[0] = " "
                netmask.lstrip!
            end

            # check if we have any non numeric characters
            if (netmask =~ /\D/)
                raise ValidationError, "#{netmask} contains invalid characters."
            end

            netmask = netmask.to_i
            if (netmask > max_bits || netmask == 0 )
                raise ValidationError, "Netmask, #{netmask}, is out of bounds for IPv#{version}." 
            end

        end
        
    elsif (netmask.kind_of?(Integer) )
        if (!packed)
            if (netmask > max_bits || netmask == 0 )
                raise ValidationError, "Netmask, #{netmask}, is out of bounds for IPv#{version}." 
            end
        else
            if (netmask >= 2**max_bits || netmask == 0 )
                raise ValidationError, "Packed netmask, #{netmask}, is out of bounds for IPv#{version}."
            end
        end
        
    else
        raise ArgumentError, "Integer or String expected for argument 'netmask' but " +
                             "#{netmask.class} provided." if (!netmask.kind_of?(String) && !netmask.kind_of?(Integer))
    end

    return(true)
end

.wildcard(ip) ⇒ Object

Synopsis

Convert a wildcard IP into a valid CIDR address. Wildcards must always be at the end of the address. Any data located after the first wildcard will be lost. Shorthand notation is prohibited for IPv6 addresses. IPv6 encoded IPv4 addresses are not currently supported.

Examples: NetAddr.wildcard(‘192.168.*’) NetAddr.wildcard(‘192.168.1.*’) NetAddr.wildcard(‘fec0:*’) NetAddr.wildcard(‘fec0:1:*’)

Arguments:

  • Wildcard IP address as a String

Returns:

  • CIDR object



1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
# File 'lib/methods.rb', line 1265

def wildcard(ip)
    version = 4

    # do operations per version of address
    if (ip =~ /\./ && ip !~ /:/)
        octets = []
        mask = 0

        ip.split('.').each do |x|
            if (x =~ /\*/)
                break
            end
            octets.push(x)
        end
        
        octets.length.times do
            mask = mask << 8
            mask = mask | 0xff
        end
        
        until (octets.length == 4)
            octets.push('0')
            mask = mask << 8
        end
        ip = octets.join('.')
        
    elsif (ip =~ /:/)
        version = 6
        fields = []
        mask = 0

        raise ArgumentError, "IPv6 encoded IPv4 addresses are unsupported." if (ip =~ /\./)
        raise ArgumentError, "Shorthand IPv6 addresses are unsupported." if (ip =~ /::/)

        ip.split(':').each do |x|
            if (x =~ /\*/)
                break
            end
            fields.push(x)
        end

        fields.length.times do
            mask = mask << 16
            mask = mask | 0xffff
        end

        until (fields.length == 8)
            fields.push('0')
            mask = mask << 16
        end
        ip = fields.join(':')
    end
        
    # make & return cidr
    cidr = NetAddr::CIDR.create(ip, :PackedNetmask => mask, :Version => version)
    return(cidr)
end