CIDR class
Ruby
Switch branches/tags
Nothing to show
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
mrblib
test
LICENSE.txt
README.md
mrbgem.rake

README.md

mruby-cidr

CIDR class

Description

mruby-cidr provides CIDR class for mruby.

It generates CIDR object which has #to_regexp method. So, it is useful to check whether ipaddr matches CIDR or not.

Demo

For example when using with Rack interface.

The following can controlls the access based on ALLOW_CIDRS.

ALLOW_CIDRS = %w(
192.168.0.2/32
10.0.0.0/8
)

class Acl
  def initialize(*args)
    @allow_regexps = ALLOW_CIDRS.map {|cidr| CIDR.new(cidr).to_regexp }
    super
  end

  def call(env)
    if @allow_regexps.select {|allow_regexp| env['REMOTE_ADDR'] =~ allow_regexp }.empty?
      [403, {'Content-Type' => 'text/plain;charset=utf-8'}, ['Forbidden']]
    else
      [399, {}, []]
    end
  end
end

Acl.new

In this case, the access from 8.8.8.8 is returned Forbidden.

Usage

p CIDR.new('10.0.0.0/8').ipaddr
#=> "10.0.0.0"
p CIDR.new('10.0.0.0/8').netmask
#=> "8"
p CIDR.new('10.0.0.0/8').decimal_mask
#=> "255.0.0.0"
p CIDR.new('10.0.0.0/255.0.0.0').bit_mask
#=> "8"
p CIDR.new('10.0.0.0/8').size
#=> 16777216
p CIDR.new('10.0.0.0/8').to_s
#=> "10.0.0.0/8"
p CIDR.new('10.0.0.0/8').to_regexp
#=> /10\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/

Requirements

  • mruby 1.2.0 or higher(recommended)

mruby-cidr depends on below.

  • mruby-onig-regexp

Installation

Add this line to build_config.rb.

conf.gem mgem: 'mruby-cidr'

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/kaihar4/mruby-cidr.

License

MIT License