From 5ee3a78242204850f8b5ed8c5b772a0d2378bebb Mon Sep 17 00:00:00 2001 From: Philip Prindeville Date: Sun, 22 Oct 2023 13:32:06 -0600 Subject: [PATCH] base-files: ipcalc.sh: Add support for decimal output This is useful if you later need to perform numeric range-checking on addresses, i.e. to see if an address falls inside a CIDR range, etc. and what interface it corresponds to. Signed-off-by: Philip Prindeville --- package/base-files/files/bin/ipcalc.sh | 38 +++++++++++++++++++++----- 1 file changed, 31 insertions(+), 7 deletions(-) diff --git a/package/base-files/files/bin/ipcalc.sh b/package/base-files/files/bin/ipcalc.sh index 0bd6edd07a..e6592e2b4a 100755 --- a/package/base-files/files/bin/ipcalc.sh +++ b/package/base-files/files/bin/ipcalc.sh @@ -4,11 +4,35 @@ PROG="$(basename "$0")" +# hook for library function +_ip2str() { + local var="$1" n="$2" + assert_uint32 "$n" || exit 1 + + if [ "$decimal" -ne 0 ]; then + export -- "$var=$n" + elif [ "$hexadecimal" -ne 0 ]; then + export -- "$var=$(printf "%x" "$n")" + else + ip2str "$@" + fi +} + usage() { - echo "Usage: $PROG address/prefix [ start limit ]" >&2 + echo "Usage: $PROG [ -d | -x ] address/prefix [ start limit ]" >&2 exit 1 } +decimal=0 +hexadecimal=0 +if [ "$1" = "-d" ]; then + decimal=1 + shift +elif [ "$1" = "-x" ]; then + hexadecimal=1 + shift +fi + if [ $# -eq 0 ]; then usage fi @@ -51,14 +75,14 @@ hostmask=$((netmask ^ 0xffffffff)) network=$((ipaddr & netmask)) broadcast=$((network | hostmask)) -ip2str IP "$ipaddr" -ip2str NETMASK "$netmask" -ip2str NETWORK "$network" +_ip2str IP "$ipaddr" +_ip2str NETMASK "$netmask" +_ip2str NETWORK "$network" echo "IP=$IP" echo "NETMASK=$NETMASK" if [ "$prefix" -le 30 ]; then - ip2str BROADCAST "$broadcast" + _ip2str BROADCAST "$broadcast" echo "BROADCAST=$BROADCAST" fi echo "NETWORK=$NETWORK" @@ -95,8 +119,8 @@ if [ "$start" -gt "$end" ]; then exit 1 fi -ip2str START "$start" -ip2str END "$end" +_ip2str START "$start" +_ip2str END "$end" if [ "$start" -le "$ipaddr" ] && [ "$ipaddr" -le "$end" ]; then echo "error: address $IP inside range $START..$END" >&2 -- 2.30.2