From 6cdc429a484392afb4ca7c8a32355987d9e0cc73 Mon Sep 17 00:00:00 2001 From: Philip Prindeville Date: Fri, 3 Nov 2023 21:11:49 -0600 Subject: [PATCH] base-files: ipcalc.sh: Add prefix-to-netmask conversion Seems like it might be used in other places, so factor it into the library. Signed-off-by: Philip Prindeville --- package/base-files/files/bin/ipcalc.sh | 2 +- package/base-files/files/lib/functions/ipv4.sh | 13 +++++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/package/base-files/files/bin/ipcalc.sh b/package/base-files/files/bin/ipcalc.sh index 2ddfbb3aba..4f48e0a792 100755 --- a/package/base-files/files/bin/ipcalc.sh +++ b/package/base-files/files/bin/ipcalc.sh @@ -55,7 +55,7 @@ case "$1" in printf "Prefix out of range (%s)\n" "$prefix" >&2 exit 1 fi - netmask=$(((0xffffffff << (32 - prefix)) & 0xffffffff)) + prefix2netmask netmask "$prefix" || exit 1 shift ;; *) diff --git a/package/base-files/files/lib/functions/ipv4.sh b/package/base-files/files/lib/functions/ipv4.sh index e12f6f56a7..9405a63552 100644 --- a/package/base-files/files/lib/functions/ipv4.sh +++ b/package/base-files/files/lib/functions/ipv4.sh @@ -144,3 +144,16 @@ ip2str() { export -- "$__var=$((__n >> 24)).$(((__n >> 16) & 255)).$(((__n >> 8) & 255)).$((__n & 255))" } +# convert prefix into an integer bitmask +prefix2netmask() { + local __var="$1" __n="$2" + assert_uint32 "$__n" || return 1 + + if [ "$__n" -gt 32 ]; then + printf "Prefix out-of-range (%s)" "$__n" >&2 + return 1 + fi + + export -- "$__var=$(((~(uint_max >> __n)) & uint_max))" +} + -- 2.30.2