Ruby port of range2cidr. Convert IP ranges to set of CIDR.
1 2 #!/usr/bin/env ruby 3 # -*- coding: utf-8 -*- 4 # $Hg: range_cidr.rb,v af9566d89389 2007-04-12 20:28 +0400 $ 5 # (C) 2007 under terms of LGPL v2.1 6 # by Vsevolod S. Balashov <vsevolod@balashov.name> 7 # 8 # backported from perl code 9 # http://www.irbs.net/internet/postfix/0401/att-3032/cidr_range.pl.gz 10 11 def range_cidr(first, last, &block) 12 if first < last 13 idx1 = 32 14 idx1 -= 1 while first[idx1] == last[idx1] 15 prefix = first >> idx1+1 << idx1+1 16 17 idx2 = 0 18 idx2 += 1 while idx2 <= idx1 and first[idx2] == 0 and last[idx2] == 1 19 20 if idx2 <= idx1 21 range_cidr(first, prefix | 2**idx1-1, &block) 22 range_cidr(prefix | 1 << idx1, last, &block) 23 else 24 yield prefix, 32-idx2 25 end 26 else 27 yield first, 32 28 end 29 end
Example Usage
1 2 #!/usr/bin/env ruby 3 # $Hg: range2cidr.rb,v 2142c33ada8b 2007-04-11 23:14 +0400 $ 4 # (C) 2007 under terms of GPL v2 5 # by Vsevolod S. Balashov <vsevolod@balashov.name> 6 # 7 # example usage of range_cidr.rb 8 9 require 'lib/range_cidr' 10 require 'ipaddr' 11 require 'socket' 12 13 if __FILE__ == $0 14 if ARGV.size == 2 15 range_cidr(IPAddr.new(ARGV[0]).to_i, IPAddr.new(ARGV[1]).to_i) { |subnet, mask| 16 puts "#{IPAddr.new(subnet, Socket::AF_INET).to_s}/#{mask}" } 17 else 18 puts "usage: range2cidr <first_ip> <last_ip>" 19 puts "example: range2cidr 192.168.1.0 192.168.2.255" 20 end 21 end
Type in terminal and look result
1 2 $ ruby range2cidr.rb 192.168.1.0 192.168.2.255 3 192.168.1.0/24 4 192.168.2.0/24
I hate perl.