base-files: ipcalc.sh: Add prefix-to-netmask conversion
authorPhilip Prindeville <philipp@redfish-solutions.com>
Sat, 4 Nov 2023 03:11:49 +0000 (21:11 -0600)
committerPhilip Prindeville <philipp@redfish-solutions.com>
Tue, 12 Dec 2023 19:30:35 +0000 (12:30 -0700)
Seems like it might be used in other places, so factor it into the
library.

Signed-off-by: Philip Prindeville <philipp@redfish-solutions.com>
package/base-files/files/bin/ipcalc.sh
package/base-files/files/lib/functions/ipv4.sh

index 2ddfbb3abaf4c4713f906752a4b28392f72d6da0..4f48e0a79271fb12c98b91ffc3c37462e93684d1 100755 (executable)
@@ -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
     ;;
 *)
index e12f6f56a766d5d51e845a9d58441d4cb165af66..9405a635525df5410a71f22d667157d69ee46c23 100644 (file)
@@ -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))"
+}
+