Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Netmask to CIDR in ruby

Tags:

ruby

ip

I've been using the ip-address gem and it doesn't seem to have the ability to convert from a netmask of the form

255.255.255.0 

into the CIDR form

/24

Does anyone have an ideas how to quickly convert the former to the latter ?

like image 979
Dean Smith Avatar asked Dec 01 '09 12:12

Dean Smith


2 Answers

Just as a FYI, and to keep the info easily accessible for those who are searching...

Here's a simple way to convert from CIDR to netmask format:

def cidr_to_netmask(cidr)
  IPAddr.new('255.255.255.255').mask(cidr).to_s
end

For instance:

cidr_to_netmask(24) #=> "255.255.255.0"
cidr_to_netmask(32) #=> "255.255.255.255"
cidr_to_netmask(16) #=> "255.255.0.0"
cidr_to_netmask(22) #=> "255.255.252.0"
like image 57
the Tin Man Avatar answered Nov 18 '22 15:11

the Tin Man


Here is the quick and dirty way

require 'ipaddr'
puts IPAddr.new("255.255.255.0").to_i.to_s(2).count("1")

There should be proper function for that, I couldn't find that, so I just count "1"

If you're going to be using the function in a number of places and don't mind monkeypatching, this could help:

IPAddr.class_eval
  def to_cidr
    "/" + self.to_i.to_s(2).count("1")
  end
end

Then you get

IPAddr.new('255.255.255.0').to_cidr
# => "/24"
like image 25
YOU Avatar answered Nov 18 '22 14:11

YOU