Module: IPAdmin
- Defined in:
- lib/eui.rb,
lib/cidr.rb,
lib/tree.rb,
lib/methods.rb
Defined Under Namespace
Classes: CIDR, EUI, NetStruct, Tree
Class Method Summary collapse
-
.compare(obj1, obj2) ⇒ Object
Compare CIDR or NetStruct objects, and determine if one is the supernet of the other.
-
.create_net_struct(object) ⇒ Object
Create a NetStruct object from an CIDR or NetStruct object.
-
.merge(options) ⇒ Object
Given a list of CIDR or NetStruct objects merge (supernet) them in the most efficient way possible.
-
.minimum_size(options) ⇒ Object
Given the number of IP addresses required in a subnet, return the minimum netmask required for that subnet.
-
.pack_ip_addr(options) ⇒ Object
Convert IP addresses into an integer.
-
.pack_ip_netmask(options) ⇒ Object
Convert IP netmask into an integer.
-
.range(options) ⇒ Object
Given two IPAdmin::CIDR objects of the same version, return all IP addresses between them (non-inclusive).
-
.shorten(addr) ⇒ Object
Take a standard IPv6 address, and format it in short-hand notation.
-
.sort(list) ⇒ Object
Given a list of IPAdmin::CIDR or NetStruct objects sort them from lowest to highest by Network/Netmask.
-
.unpack_ip_addr(options) ⇒ Object
Unack a packed IP address back into a printable string.
-
.unpack_ip_netmask(options) ⇒ Object
Unack a packed IP netmask into a integer representing the number of bits in the CIDR mask.
-
.unshorten(addr) ⇒ Object
Take an IPv6 address in short-hand format, and expand it into standard notation.
-
.validate_eui(options) ⇒ Object
Validate an EUI-48 or EUI-64 address.
-
.validate_ip_addr(options) ⇒ Object
Validate an IP address.
-
.validate_ip_netmask(options) ⇒ Object
Validate IP Netmask.
Class Method Details
.compare(obj1, obj2) ⇒ Object
Compare CIDR or NetStruct objects, and determine if one is the supernet of the other.
-
Arguments:
-
Two CIDR or NetStruct objects
-
-
Returns:
-
if one object is a subnet of another, then return an array in order of
- supernet,subnet
-
if both are equal, return 1
-
if neither is a supernet of the other, return nil
-
Example:
supernet,subnet = IPAdmin.compare(cidr1,cidr2)
30 31 32 33 34 35 36 37 38 39 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 |
# File 'lib/methods.rb', line 30 def compare(obj1,obj2) ret_val = nil # validate arguments if ( !obj1.kind_of?(IPAdmin::CIDR) && !obj1.kind_of?(IPAdmin::NetStruct) ) raise ArgumentError, "Expected IPAdmin::CIDR or NetStruct " + "as first argument, but #{obj1.class} provided." end if ( !obj2.kind_of?(IPAdmin::CIDR) && !obj2.kind_of?(IPAdmin::NetStruct) ) raise ArgumentError, "Expected IPAdmin::CIDR or NetStruct " + "as second argument, but #{obj2.class} provided." end # make sure both are same version if (obj1.version != obj2.version ) raise ArgumentError, "Provided objects are of different IP versions." end # get network/netmask of each objects = [obj1,obj2] networks = [] netmasks = [] for obj in objects if ( obj.kind_of?(IPAdmin::CIDR) ) networks.push(obj.packed_network) netmasks.push(obj.packed_netmask) elsif ( obj.kind_of?(IPAdmin::NetStruct) ) networks.push(obj.network) netmasks.push(obj.netmask) end end # return 1's if objects are equal otherwise # whichever netmask is smaller will be the supernet. # if we '&' both networks by the supernet, and they are # equal, then the supernet is the parent of the other network if ( (networks[0] == networks[1]) && (netmasks[0] == netmasks[1]) ) ret_val = 1 elsif (netmasks[0] < netmasks[1]) if ( (netmasks[0] & networks[0]) == (netmasks[0] & networks[1]) ) ret_val = [obj1,obj2] end elsif (netmasks[1] < netmasks[0]) if ( (netmasks[1] & networks[0]) == (netmasks[1] & networks[1]) ) ret_val = [obj2,obj1] end end return(ret_val) end |
.create_net_struct(object) ⇒ Object
Create a NetStruct object from an CIDR or NetStruct object. This type of Struct is used internally for various tasks, and is not likely to be useful to anyone.
-
Arguments:
-
CIDR or NetStruct object
-
-
Returns:
-
NetStruct object
-
Example:
net_struct = IPAdmin.create_net_struct(object)
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 |
# File 'lib/methods.rb', line 110 def create_net_struct(object) if ( object.kind_of?(IPAdmin::CIDR) ) network = object.packed_ip netmask = object.packed_netmask elsif ( object.kind_of?(IPAdmin::NetStruct) ) network = object.network netmask = object.netmask else raise ArgumentError, "Expected IPAdmin::CIDR or NetStruct "+ "object, but #{object.class} provided." end version = object.version net_struct = NetStruct.new(network,netmask,version,object,[]) return(net_struct) end |
.merge(options) ⇒ Object
Given a list of CIDR or NetStruct objects merge (supernet) them in the most efficient way possible. Supernetting will only occur when the newly created supernet will not result in the ‘creation’ of additional space. For example the following blocks (192.168.0.0/24, 192.168.1.0/24, and 192.168.2.0/24) would merge into 192.168.0.0/23 and 192.168.2.0/24 rather than into 192.168.0.0/22
-
Arguments:
-
Hash with the following fields:
- :List -- Array of CIDR or NetStruct objects - :NetStruct -- if true, return IPAdmin::NetStruct objects (optional) - :Objectify -- if true, return IPAdmin::CIDR objects (optional) - :Short -- if true, return IPv6 addresses in short-hand notation (optional)
-
-
Returns:
-
Array of CIDR or NetStruct objects
-
-
Notes:
-
I have designed this with enough flexibility that you can pass in CIDR addresses that arent even related (ex. 192.168.1.0/26, 192.168.1.64/26, 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 = IPAdmin.merge(:List => list)
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 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 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 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 362 363 364 365 366 367 368 |
# File 'lib/methods.rb', line 166 def merge() version = nil short = false objectify = false # validate options if ( !.kind_of?(Hash) ) raise ArgumentError, "Hash expected but #{.class} provided." end if (!.has_key?(:List)) raise ArgumentError, "Missing argument: List." end if (.has_key?(:Short) && [:Short] == true) short = true end if (.has_key?(:Objectify) && [:Objectify] == true) objectify = true end list = [:List] ret_struct = 1 if (.has_key?(:NetStruct)) # make sure list is an array if ( !list.kind_of?(Array) ) raise ArgumentError, "Expected Array for option :List, " + "but #{list.class} provided." end # make sure all are valid types of the same IP version list.each do |obj| if (!obj.kind_of?(IPAdmin::CIDR) && !obj.kind_of?(IPAdmin::NetStruct) ) raise ArgumentError, "Expected IPAdmin::CIDR or NetStruct " + "object but #{obj.class} provided." end version = obj.version if (!version) if (!obj.version == version) raise "Provided objects must be of the same IP version." end end # make all_f if (version == 4) all_f = 2**32 - 1 else all_f = 2**128 - 1 end # make sure that our list is in order, and contains no duplicates list = IPAdmin.sort(list) index = 0 (list.length).times do if ((index > 0)&&(IPAdmin.compare(list[index],list[index-1]) == 1)) list.delete_at(index) else index += 1 end end # create supernet_list from list supernet_list = [] list.each do |obj| if (obj.kind_of?(IPAdmin::CIDR)) supernet_list.push(IPAdmin.create_net_struct(obj)) elsif ( obj.kind_of?(IPAdmin::NetStruct) ) if (obj.subnets && obj.subnets.length > 0) # get all child subnets of this branch entry children = merge(:List => obj.subnets, :NetStruct => 1) # if any child subnets are equal to the parent subnet # then copy the grandchild subnets and delete the child children.each do |child| if ( (obj.network == child.network) && (obj.netmask == child.netmask) ) if (child.subnets && child.subnets.length > 0) grandchildren = child.subnets children.concat(grandchildren) end children.delete(child) children = IPAdmin.sort(children) break end end obj.subnets.clear obj.subnets.concat(children) end supernet_list.push(obj) end end # merge subnets of this new branch by removing them from 'supernet_list', # and categorizing them into hash of arrays (key=netmask) # within each categorization we merge contiguous subnets # and then remove them from that category & put them back into # 'supernet_list'. we do this until our 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 |entry| netmask = entry.netmask if (categories.has_key?(netmask) ) (categories[netmask]).push(entry) else categories[netmask] = [entry] end end supernet_list.clear categories.each_key do |netmask| entries = categories[netmask] bitstep = (all_f + 1) - netmask # this entire process depends on the list being in order until (entries.length == 0) to_merge = [] multiplier = 1 first = entries[0] num_required = 2**multiplier supermask = (netmask << multiplier) & all_f supernet = supermask & first.network if (first.network == supernet) # take first entry and use it to form a base # supernet address. this supernet should have # x number of subnets in it, so we look for # those subnets & if found store them expected = first.network entries.each do |entry| if ( (entry.network == expected) && (first.network == supernet) ) to_merge.push(entry) expected = expected + bitstep if ( (to_merge.length == num_required) && (entries.length > num_required ) ) multiplier += 1 num_required = 2**multiplier supermask = (netmask << multiplier) & all_f supernet = supermask & first.network end else # if entry is a duplicate, then kill it if (IPAdmin.compare(entry,to_merge.last) == 1) entries.delete(entry) end break end end else to_merge.push(first) end # make sure we actually have all of our subnets # create our new supernet if (to_merge.length != num_required) multiplier -= 1 supermask = (netmask << multiplier) & all_f supernet = supermask & first.network end net_struct = NetStruct.new(supernet,supermask,version,nil,[]) # now that we have the child members of our new supernet # take any grandchild subnets that they may have and # add them to the new supernet. then kill the children (2**multiplier).times do to_kill = to_merge.shift net_struct.subnets.concat(to_kill.subnets) if (to_kill.subnets) entries.delete(to_kill) end supernet_list.push(net_struct) end end categories.clear supernet_list = IPAdmin.sort(supernet_list) end # if '!ret_struct', return CIDR's if (!ret_struct) supernets = [] supernet_list.each do |entry| if (!objectify) network = IPAdmin.unpack_ip_addr(:Integer => entry.network, :Version => version) network = IPAdmin.shorten(network) if (short && version == 6) netmask = IPAdmin.unpack_ip_netmask(:Integer => entry.netmask, :Version => version) supernets.push("#{network}/#{netmask}") else supernets.push(IPAdmin::CIDR.new(:PackedIP => entry.network, :PackedNetmask => entry.netmask, :Version => version)) end end else supernets = supernet_list end return(supernets) end |
.minimum_size(options) ⇒ Object
Given the number of IP addresses required in a subnet, return the minimum netmask required for that subnet.
-
Arguments:
-
Hash with the following fields:
- :IPCount -- the number of IP addresses required - Integer - :Version -- IP version - Integer(optional)
-
-
Returns:
-
Integer
-
-
Notes:
-
Version is assumed to be 4 unless specified otherwise.
-
Example:
netmask = IPAdmin.minumum_size(:IPCount => 14) -> 28
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 |
# File 'lib/methods.rb', line 397 def minimum_size() version = 4 if ( !.kind_of?(Hash) ) raise ArgumentError, "Hash expected but #{.class} provided." end if ( !.has_key?(:IPCount) ) raise ArgumentError, "Missing argument: List." end ipcount = [:IPCount] if (.has_key?(:Version)) version = [:Version] end if (version == 4) max_bits = 32 else max_bits = 128 end if (ipcount > 2**max_bits) raise "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(subnet_bits) end |
.pack_ip_addr(options) ⇒ Object
Convert IP addresses into an integer. No attempt at validation is performed.
-
Arguments:
-
Hash with the following fields:
- :IP -- IP address - String - :Version -- IP version - Integer
-
-
Returns:
-
Integer
-
-
Notes:
-
Will attempt to auto-detect IP version if not provided
-
Example:
pack_ip_addr(IP => '192.168.1.1')
pack_ip_addr(IP => 'ffff::1')
pack_ip_addr(IP => '::192.168.1.1')
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 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 |
# File 'lib/methods.rb', line 464 def pack_ip_addr() if (!.kind_of?(Hash)) raise ArgumentError, "Expected Hash, but #{.class} provided." end if (!.has_key?(:IP)) raise ArgumentError, "Missing argument: IP." end ip = [:IP] if (.has_key?(:Version)) version = [:Version] if (version != 4 && version != 6) raise ArgumentError, ":Version should be 4 or 6, but was '#{version}'." end end if ( ip.kind_of?(String) ) # 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 = IPAdmin.pack_ip_addr(:IP => 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, "Argument :IP should be a String, but is a #{ip.class}." end return(packed_ip) end |
.pack_ip_netmask(options) ⇒ Object
Convert IP netmask into an integer. No validation is performed. 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.
-
Arguments
-
Hash with the following fields:
- :Netmask -- Netmask - String or Integer - :Version -- IP version - Integer (optional)
-
-
Returns:
-
Integer
-
-
Notes:
-
Version defaults to 4
-
Example:
packed = IPAdmin.pack_ip_netmask(Netmask => '255.255.255.0')
packed = IPAdmin.pack_ip_netmask(Netmask => '24')
packed = IPAdmin.pack_ip_netmask(Netmask => 24)
packed = IPAdmin.pack_ip_netmask(Netmask => '/24')
packed = IPAdmin.pack_ip_netmask(Netmask => '64', :Version => 6)
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 |
# File 'lib/methods.rb', line 591 def pack_ip_netmask() if (!.kind_of?(Hash)) raise ArgumentError, "Expected Hash, but #{.class} provided." end if (!.has_key?(:Netmask)) raise ArgumentError, "Missing argument: Netmask." end netmask = [:Netmask] if (.has_key?(:Version)) version = [:Version] if (version != 4 && version != 6) raise ArgumentError, ":Version should be 4 or 6, but was '#{version}'." elsif (version == 6) all_f = 2**128-1 else all_f = 2**32-1 end else all_f = 2**32-1 end if (netmask.kind_of?(String)) if(netmask =~ /\./) packed_netmask = IPAdmin.pack_ip_addr(:IP => 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)) packed_netmask = all_f ^ (all_f >> netmask) else raise ArgumentError, "Argument :Netmask should be a String or Integer, but is a #{netmask.class}." end return(packed_netmask) end |
.range(options) ⇒ Object
Given two IPAdmin::CIDR objects of the same version, return all IP addresses between them (non-inclusive).
-
Arguments:
-
Hash with the following fields:
- :Bitstep -- enumerate in X sized steps - Integer (optional) - :Boundaries -- array of (2) CIDR objects - :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 CIDR objects
-
-
Notes:
-
IPAdmin.range will use the original IP address passed during the initialization of the CIDR objects. This IP can be found using the CIDR.ip() method.
-
Example:
list = IPAdmin.range(:Boundaries => [cidr1,cidr2])
670 671 672 673 674 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 728 729 730 731 732 733 734 735 736 737 738 739 740 741 |
# File 'lib/methods.rb', line 670 def range() list = [] bitstep = 1 objectify = false short = false limit = nil # check options if () if ( !.has_key?(:Boundaries) ) raise ArgumentError, "Missing argument: Boundaries." end if ([:Boundaries].length == 2) (cidr1,cidr2) = [:Boundaries] else raise ArgumentError, "Two IPAdmin::CIDR ojects are required. " + "as Boundaries." end if( .has_key?(:Bitstep) ) bitstep = [:Bitstep] end if( .has_key?(:Objectify) && [:Objectify] == true ) objectify = true end if( .has_key?(:Short) && [:Short] == true ) short = true end if( .has_key?(:Limit) ) limit = [:Limit] end end # check our objects if (!cidr1.kind_of?(IPAdmin::CIDR) && !cidr2.kind_of?(IPAdmin::CIDR)) raise ArgumentError, "One or more values provided under :Boundaries "+ "is not a valid IPAdmin::CIDR object." end # check version, store & sort if (cidr1.version == cidr2.version) version = cidr1.version boundaries = [cidr1.packed_ip, cidr2.packed_ip] boundaries.sort else raise ArgumentError, "Provided IPAdmin::CIDR objects are of different IP versions." end # dump our range my_ip = boundaries[0] + 1 until (my_ip >= boundaries[1]) if (!objectify) my_ip_s = IPAdmin.unpack_ip_addr(:Integer => my_ip, :Version => version) my_ips = IPAdmin.shorten(my_ips) 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 if (limit) limit = limit -1 break if (limit == 0) end end return(list) end |
.shorten(addr) ⇒ Object
Take a standard IPv6 address, and format it in short-hand notation. The address should not contain a netmask.
-
Arguments:
-
String
-
-
Returns:
-
String
-
Example:
short = IPAdmin.shorten('fec0:0000:0000:0000:0000:0000:0000:0001') --> 'fec0::1'
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 825 826 827 828 829 830 831 832 833 834 835 836 837 |
# File 'lib/methods.rb', line 765 def shorten(addr) # is this a string? if (!addr.kind_of? String) raise ArgumentError, "Expected String, but #{addr.class} provided." end validate_ip_addr(:IP => 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
Given a list of IPAdmin::CIDR or NetStruct objects sort them from lowest to highest by Network/Netmask.
-
Arguments:
-
Array of CIDR or NetStruct objects
-
-
Returns:
-
Array
-
-
Notes:
-
IPAdmin.sort will use the original IP address passed during the initialization of the CIDR objects. This IP can be found using the CIDR.ip() method.
-
Example:
sorted = IPAdmin.sort(list)
865 866 867 868 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 911 912 913 914 915 916 917 918 |
# File 'lib/methods.rb', line 865 def sort(list) # make sure list is an array if ( !list.kind_of?(Array) ) raise ArgumentError, "Array of IPAdmin::CIDR or NetStruct " + "objects expected, but #{list.class} provided." end # make sure all are valid types of the same IP version version = nil list.each do |obj| unless (obj.kind_of?(IPAdmin::CIDR) || obj.kind_of?(IPAdmin::NetStruct) ) raise ArgumentError, "Expected IPAdmin::CIDR or NetStruct " + "object but #{obj.class} provided." end version = obj.version if (!version) unless (obj.version == version) raise "Provided objects must all be of the same IP version." end end # create unsorted_list from list unsorted_list = [] list.each do |obj| unsorted_list.push(IPAdmin.create_net_struct(obj)) end # sort by network. if networks are equal, sort by netmask. sorted_list = [] unsorted_list.each do |entry| index = 0 sorted_list.each do if(entry.network < (sorted_list[index]).network) break elsif (entry.network == (sorted_list[index]).network) if (entry.netmask < (sorted_list[index]).netmask) break end end index += 1 end sorted_list.insert(index, entry) end # replace sorted_list entries with their .object index = 0 sorted_list.length.times do sorted_list[index] = (sorted_list[index]).object index += 1 end return(sorted_list) end |
.unpack_ip_addr(options) ⇒ Object
Unack a packed IP address back into a printable string. No attempt at validation is performed.
-
Arguments:
-
Hash with the following fields:
- :Integer -- Integer representaion of an IP address - :Version -- IP version - Integer (optional) - :IPv4Mapped -- if true, unpack IPv6 as an IPv4 mapped address (optional)
-
-
Returns:
-
String
-
-
Notes:
-
IP version will attempt to be auto-detected if not provided
-
Example:
unpacked = IPAdmin.unpack_ip_addr(:Integer => packed)
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 974 975 976 977 978 979 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 |
# File 'lib/methods.rb', line 948 def unpack_ip_addr() ipv4_mapped = false if (!.kind_of?(Hash)) raise ArgumentError, "Expected Hash, but #{.class} provided." end if (!.has_key?(:Integer)) raise ArgumentError, "Missing argument: Integer." end packed_ip = [:Integer] if (!packed_ip.kind_of?(Integer)) raise ArgumentError, "Expected Integer, but #{.class} provided for argument: Integer." end if (.has_key?(:Version)) version = [:Version] if (version != 4 && version != 6) raise ArgumentError, ":Version should be 4 or 6, but was '#{version}'." end end if (.has_key?(:IPv4Mapped) && [:IPv4Mapped] == true) ipv4_mapped = true end # 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 = IPAdmin.unpack_ip_addr(:Integer => 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(options) ⇒ Object
Unack a packed IP netmask into a integer representing the number of bits in the CIDR mask. No attempt at validation is performed.
-
Arguments:
-
Hash with the following fields:
- :Integer -- Integer representation of an IP Netmask
-
-
Returns:
-
Integer
-
Example:
unpacked = IPAdmin.unpack_ip_netmask(:Integer => packed)
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 |
# File 'lib/methods.rb', line 1045 def unpack_ip_netmask() if (!.kind_of?(Hash)) raise ArgumentError, "Expected Hash, but #{.class} provided." end if (!.has_key?(:Integer)) raise ArgumentError, "Missing argument: Integer." end packed_netmask = [:Integer] if (!packed_netmask.kind_of?(Integer)) raise ArgumentError, "Argument :Integer should be an Integer, but is a #{packed_netmask.class}." end if (packed_netmask < 2**32) mask = 32 else 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(addr) ⇒ Object
Take an IPv6 address in short-hand format, and expand it into standard notation. The address should not contain a netmask.
-
Arguments:
-
String
-
-
Returns:
-
String
-
Example:
long = IPAdmin.unshorten('fec0::1') --> 'fec0:0000:0000:0000:0000:0000:0000:0001'
1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 |
# File 'lib/methods.rb', line 1098 def unshorten(addr) # is this a string? if (!addr.kind_of? String) raise ArgumentError, "Expected String, but #{addr.class} provided." end validate_ip_addr(:IP => addr, :Version => 6) ipv4_mapped = true if (addr =~ /\./) packed = pack_ip_addr(:IP => addr, :Version => 6) if (!ipv4_mapped) long = unpack_ip_addr(:Integer => packed, :Version => 6) else long = unpack_ip_addr(:Integer => packed, :Version => 6, :IPv4Mapped => true) end return(long) end |
.validate_eui(options) ⇒ Object
Validate an EUI-48 or EUI-64 address.
-
Arguments
-
Hash with the following fields:
- :EUI -- Address to validate - String
-
-
Returns:
-
True
-
-
Example:
-
IPAdmin.validate_eui(:EUI => ‘01-00-5e-12-34-56’)
-
1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 |
# File 'lib/methods.rb', line 1140 def validate_eui() if (!.kind_of? Hash) raise ArgumentError, "Expected Hash, but #{.class} provided." end if (!.has_key?(:EUI)) raise ArgumentError, "Missing argument: EUI." end eui = [:EUI] if (eui.kind_of?(String)) # check for invalid characters if (eui =~ /[^0-9a-fA-f\.\-\:]/) raise "#{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 "#{eui} is invalid (unrecognized formatting)." end elsif (eui =~ /\:/) fields = eui.split(':') if (fields.length != 6 && fields.length != 8) raise "#{eui} is invalid (unrecognized formatting)." end elsif (eui =~ /\./) fields = eui.split('.') if (fields.length != 3 && fields.length != 4) raise "#{eui} is invalid (unrecognized formatting)." end else raise "#{eui} is invalid (unrecognized formatting)." end else raise ArgumentError, "Expected String, but #{eui.class} " + "provided for argument :EUI." end return(true) end |
.validate_ip_addr(options) ⇒ Object
Validate an IP address. The address should not contain a netmask.
-
Arguments
-
Hash with the following fields:
- :IP -- IP address to validate - String or Integer - :Version -- IP version - Integer (optional)
-
-
Returns:
-
True
-
-
Notes:
-
IP version will attempt to be auto-detected if not provided
-
Example:
validate_ip_addr(IP => '192.168.1.1')
validate_ip_addr(IP => 'ffff::1')
validate_ip_addr(IP => '::192.168.1.1')
validate_ip_addr(IP => 0xFFFFFF)
validate_ip_addr(IP => 2**128-1)
validate_ip_addr(IP => 2**32-1, :Version => 4)
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 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 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 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 |
# File 'lib/methods.rb', line 1214 def validate_ip_addr() if (!.kind_of?(Hash)) raise ArgumentError, "Expected Hash, but #{.class} provided." end if (!.has_key?(:IP)) raise ArgumentError, "Missing argument: IP." end ip = [:IP] if (.has_key?(:Version)) version = [:Version] if (version != 4 && version != 6) raise ArgumentError, ":Version should be 4 or 6, but was '#{version}'." end end if ( ip.kind_of?(String) ) # check validity of charaters if (ip =~ /[^0-9a-fA-F\.:]/) raise "#{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 "#{ip} is invalid (IPv4 requires (4) octets)." if (octets.length != 4) # are octets in range 0..255? octets.each do |octet| raise "#{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 "#{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 "#{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 "#{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 "#{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 "#{ip} is invalid (Legacy IPv4 portion of IPv6 " + "address should contain (4) octets)." if (octets.length != 4) octets.each do |x| raise "#{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 "#{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 "#{ip} is invalid (IPv6 address contains invalid hex characters)." else x = x.to_i(16) if ( (x < 0) || (x >= 2**16) ) raise "#{ip} is invalid (Fields of an IPv6 address " + "should be between 0x0 and 0xFFFF)." end end end else raise "#{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 "#{ip} is invalid (Integer is out of bounds)." if ( (ip < 0) || (ip > 2**32) ) else raise "#{ip} is invalid (Integer is out of bounds)." if ( (ip < 0) || (ip > 2**128) ) end else raise ArgumentError, "Expected String or Integer, but #{ip.class} provided." end return(true) end |
.validate_ip_netmask(options) ⇒ Object
Validate IP Netmask.
-
Arguments:
-
Hash with the following fields:
- :Netmask -- Netmask to validate - String or Integer - :Packed -- if true, the provided Netmask is a packed Integer - :Version -- IP version - Integer (optional)
-
-
Returns:
-
True or exception.
-
-
Notes:
-
Version defaults to 4 if not specified.
-
Example:
IPAdmin.validate_ip_netmask(:Netmask => '/32')
IPAdmin.validate_ip_netmask(:Netmask => 32)
IPAdmin.validate_ip_netmask(:Netmask => 0xffffffff, :Packed => true)
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 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 |
# File 'lib/methods.rb', line 1377 def validate_ip_netmask() packed = false if (!.kind_of?(Hash)) raise ArgumentError, "Expected Hash, but #{.class} provided." end if (!.has_key?(:Netmask)) raise ArgumentError, "Missing argument: Netmask." end netmask = [:Netmask] if (.has_key?(:Packed) && [:Packed] == true) packed = true end if (.has_key?(:Version)) version = [: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 else version = 4 max_bits = 32 end if (netmask.kind_of?(String)) if(netmask =~ /\./) all_f = 2**32-1 packed_netmask = 0 # validate & pack extended mask begin validate_ip_addr(:IP => netmask) packed_netmask = pack_ip_addr(:IP => netmask) rescue Exception raise "#{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 "#{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 "#{netmask} contains invalid characters." end netmask = netmask.to_i if (netmask > max_bits || netmask == 0 ) raise "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 "Netmask, #{netmask}, is out of bounds for IPv#{version}." end else if (netmask >= 2**max_bits || netmask == 0 ) raise "Packed netmask, #{netmask}, is out of bounds for IPv#{version}." end end else raise ArgumentError, "Expected String or Integer, but #{netmask.class} provided." end return(true) end |