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 ?
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 ?
The code achieves the masking by accessing private instance variable *@mask_addr) of IPAddr instance (address, passed into serialize_ipaddr). This is not recommended way (as the instance variables are not part of the classes public API but here it's better than parsing the string from #inspect in my opinion.
So the process is as follows:
255.255.255.0 -> 4294967040 -> 11111111111111111111111100000000
EDIT: Added explanation to the implementation as requested by NathanOliver
If you don't need to use ip-address gem, you can do this with the netaddr gem
Here's a more mathematical approach, avoiding strings at all costs:
with "mask" being a string like 255.255.255.0. You can modify it and change the first argument to just "mask" if "mask" is already an integer representation of an IP address.
So for example, if mask was "255.255.255.0", IPAddr.new(mask,Socket::AF_INET).to_i would become 0xffffff00, which is then xor'd with 0xffffffff, which equals 255.
We add 1 to that to make it a complete range of 256 hosts, then find the log base 2 of 256, which equals 8 (the bits used for the host address), then subtract that 8 from 32, which equals 24 (the bits used for the network address).
We then cast to integer because Math.log2 returns a float.
Here is the quick and dirty way
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:
Then you get
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:
For instance:
Quick and dirty conversion:
"255.255.255.0".split(".").map { |e| e.to_i.to_s(2).rjust(8, "0") }.join.count("1").split(".")
=> I split mask in an Array
.map { |e| e.to_i.to_s(2).rjust(8, "0") }
=> For each element in Array:
.to_i
=> Convert into integer
.to_s(2)
=> Convert integer into binary
.rjust(8, "0")
=> Add padding
=> Map return a Array with same cardinality
.join
=> Convert Array into a full string
.count("1")
=> Count "1" characters => Give CIDR mask