Ruby: Convert CIDR to Netmask

479 Views Asked by At

Given a network definition like 192.168.1.0/24, I'd like to convert the /24 CIDR to a four digit netmask, in this case 255.255.255.0.

No extra gems should be used.

2

There are 2 best solutions below

1
Kalsan On

Ruby's IPAddr does not appear to expose this functionality. However, it contains a private instance variable called @mask_addr that contains the integer value of the desired mask.

It can be represented as a four digit submask by converting it back to another IPAddr instance:

require "ipaddr"

net = IPAddr.new("192.168.1.0/24")
subnet = IPAddr.new(net.instance_variable_get(:@mask_addr), Socket::AF_INET).to_s
# => "255.255.255.0"
1
tadman On

The actual method here is pretty simple:

def mask(n)
  [ ((1 << 32) - 1) << (32 - n) ].pack('N').bytes.join('.')
end

Where that can give you results like:

mask(24)
# => "255.255.255.0"
mask(16)
# => "255.255.0.0"
mask(22)
# => "255.255.252.0"