Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert from ipaddr to netaddr:cidr type

Using ruby 2.0.0, how can I convert an object of type IPAddr to a NetAddr::CIDR?

Example:

IPAddr.new("1a03:a240:0100::/56")
IPAddr.new("192.1268.1.0/24")

This does not work, as I doesn't respect the netmask/ prefix:

NetAddr::CIDR.create(IPAddr.new("1a03:a240:0100::/56").to_s).to_s
=> "1a03:a240:0100:0000:0000:0000:0000:0000/128"
like image 426
gucki Avatar asked Dec 06 '25 21:12

gucki


1 Answers

Here's another solution we use at Discourse

class IPAddr

  def to_cidr_s
    if @addr
      mask = @mask_addr.to_s(2).count('1')
      "#{to_s}/#{mask}"
    else
      nil
    end
  end

end
like image 110
ZogStriP Avatar answered Dec 09 '25 17:12

ZogStriP