Network engineers and sysadmins frequently need to convert between CIDR notation and dotted-decimal netmask format. While some can do this conversion mentally, it's error-prone and time-consuming. Here are several command-line tools available in Ubuntu/Debian that can help:
The ipcalc
tool is perhaps the most comprehensive solution:
sudo apt install ipcalc
ipcalc 255.255.255.224
Sample output:
NETMASK=255.255.255.224
PREFIX=27
...
For more detailed network calculations:
sudo apt install sipcalc
sipcalc 255.255.255.224
This provides extensive network information including CIDR notation, network range, and broadcast address.
For scripting purposes, Python's ipaddress
module is excellent:
python3 -c "import ipaddress; print(ipaddress.IPv4Network('0.0.0.0/255.255.255.224').prefixlen)"
Output: 27
For those who prefer native bash solutions:
function netmask_to_cidr() {
local netmask=$1
local x bits=0
IFS=.
for x in $netmask; do
while [ $x -gt 0 ]; do
[ $(($x%2)) -eq 1 ] && bits=$(($bits+1))
x=$(($x/2))
done
done
echo $bits
}
netmask_to_cidr 255.255.255.224
For complete network analysis, consider these additional tools:
nmcli
- NetworkManager's command-line toolnetmask
package - Providesnetmask
andcidr
commandsip
command - Built-in Linux tool for network configuration
Each tool has its strengths depending on whether you need simple conversion, full network analysis, or scripting capabilities.
Every sysadmin knows the frustration of subnet calculations. That moment when you stare at 255.255.255.224
and your brain freezes trying to convert it to CIDR notation. Luckily, Linux offers several command-line solutions.
The ipcalc
package provides comprehensive network address manipulation:
sudo apt install ipcalc
ipcalc 255.255.255.224
NETMASK=255.255.255.224
NETWORK=27
For more detailed analysis, sipcalc
is excellent:
sudo apt install sipcalc
sipcalc 255.255.255.224
-[ipv4 : 255.255.255.224]-
Network mask - 255.255.255.224
Network mask (bits) - 27
When you need quick calculations without installing tools:
python3 -c "import ipaddress; print(ipaddress.IPv4Network('0.0.0.0/255.255.255.224').prefixlen)"
Add this to your .bashrc
for permanent access:
netmask2cidr() {
local mask=$1
local x bits=0
IFS=.
for x in $mask; do
case $x in
255) bits=$((bits+8));;
254) bits=$((bits+7));;
252) bits=$((bits+6));;
248) bits=$((bits+5));;
240) bits=$((bits+4));;
224) bits=$((bits+3));;
192) bits=$((bits+2));;
128) bits=$((bits+1));;
0);;
esac
done
echo "$bits"
}
netmask
package:netmask -c 255.255.255.224
ip
command:ip route get 1.1.1.1 | grep -oP 'src \K\S+' | xargs -I{} ip route show dev {} | head -1 | grep -oP '/\K[0-9]+'
Here's how you might use these tools in a real-world scenario:
# Find all /27 networks in your routing table
ip route | awk '{print $1}' | xargs -I{} sipcalc {} | grep -B1 "Network mask (bits) - 27"