Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Ruby port of range2cidr. Convert IP ranges to set of CIDR. (See related posts)

See rfc1878 for more detail about CIDR

#!/usr/bin/env ruby
# -*- coding: utf-8 -*-
# $Hg: range_cidr.rb,v af9566d89389 2007-04-12 20:28 +0400 $
# (C) 2007 under terms of LGPL v2.1
# by Vsevolod S. Balashov <vsevolod@balashov.name>
#
# backported from perl code
# http://www.irbs.net/internet/postfix/0401/att-3032/cidr_range.pl.gz

def range_cidr(first, last, &block)
  if first < last
    idx1 = 32
    idx1 -= 1 while first[idx1] == last[idx1]
    prefix = first >> idx1+1 << idx1+1

    idx2 = 0
    idx2 += 1 while idx2 <= idx1 and first[idx2] == 0 and last[idx2] == 1

    if idx2 <= idx1
      range_cidr(first, prefix | 2**idx1-1, &block)
      range_cidr(prefix | 1 << idx1, last, &block)
    else
      yield prefix, 32-idx2
    end
  else
    yield first, 32
  end
end


Example Usage

#!/usr/bin/env ruby
# $Hg: range2cidr.rb,v 2142c33ada8b 2007-04-11 23:14 +0400 $
# (C) 2007 under terms of GPL v2
# by Vsevolod S. Balashov <vsevolod@balashov.name>
#
# example usage of range_cidr.rb

require 'lib/range_cidr'
require 'ipaddr'
require 'socket'

if __FILE__ == $0
  if ARGV.size == 2
    range_cidr(IPAddr.new(ARGV[0]).to_i, IPAddr.new(ARGV[1]).to_i) { |subnet, mask|
      puts "#{IPAddr.new(subnet, Socket::AF_INET).to_s}/#{mask}"  }
  else
    puts "usage: range2cidr <first_ip> <last_ip>"
    puts "example: range2cidr 192.168.1.0 192.168.2.255"
  end
end


Type in terminal and look result

$ ruby range2cidr.rb 192.168.1.0 192.168.2.255
192.168.1.0/24
192.168.2.0/24


I hate perl.

Comments on this post

skywriter14 posts on May 19, 2007 at 12:52
Ya, I asked Perl. She hates u too.

You need to create an account or log in to post comments to this site.


Click here to browse all 4863 code snippets

Related Posts