Skip to content

Commit

Permalink
base-files: ipcalc.sh: Add netmask2prefix function
Browse files Browse the repository at this point in the history
Also add is_contiguous to check if it's a valid netmask.

Signed-off-by: Philip Prindeville <philipp@redfish-solutions.com>
  • Loading branch information
pprindeville committed Nov 12, 2023
1 parent 55bae43 commit aa0e101
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
2 changes: 1 addition & 1 deletion package/base-files/files/bin/ipcalc.sh
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ fi
hostmask=$((netmask ^ 0xffffffff))

network=$((ipaddr & netmask))
prefix=$((32 - $(bitcount $hostmask)))
prefix=$(netmask2prefix "$netmask")
broadcast=$((network | hostmask))

count=$((hostmask + 1))
Expand Down
21 changes: 21 additions & 0 deletions package/base-files/files/lib/functions/ipv4.sh
Original file line number Diff line number Diff line change
Expand Up @@ -140,3 +140,24 @@ prefix2netmask() {
echo "$(((~(uint_max >> n)) & uint_max))"
}

# check argument as being contiguous upper bits (and yes,
# 0 doesn't have any discontiguous bits).
is_contiguous() {
local x="$(check_uint32 "$1")"

local y=$((~x & uint_max))
local z=$(((y + 1) & uint_max))

[ $((z & y)) -eq 0 ]
}

# convert mask to prefix, validating that it's a conventional
# (contiguous) netmask.
netmask2prefix() {
local n="$(check_uint32 "$1")"

is_contiguous "$n" || __die "Not a contiguous netmask ($n)"

echo "$((32 - $(bitcount $n)))"
}

0 comments on commit aa0e101

Please sign in to comment.