base-files: ipcalc.sh: Add some commentary, etc.

Explain some of the more obscure logic, or where we deviate from
what the original awk code did.  Also, give a count of the usable
addresses on the subnet.

Signed-off-by: Philip Prindeville <philipp@redfish-solutions.com>
This commit is contained in:
Philip Prindeville 2023-10-24 00:16:25 -06:00
parent 5ee3a78242
commit f0612c0d84
2 changed files with 16 additions and 0 deletions

View File

@ -4,6 +4,8 @@
PROG="$(basename "$0")"
# wrapper to convert an integer to an address, unless we're using
# decimal output format.
# hook for library function
_ip2str() {
local var="$1" n="$2"
@ -39,11 +41,13 @@ fi
case "$1" in
*/*.*)
# data is n.n.n.n/m.m.m.m format, like on a Cisco router
str2ip ipaddr "${1%/*}" || exit 1
str2ip netmask "${1#*/}" || exit 1
shift
;;
*/*)
# more modern prefix notation of n.n.n.n/p
str2ip ipaddr "${1%/*}" || exit 1
prefix="${1#*/}"
assert_uint32 "$prefix" || exit 1
@ -55,12 +59,14 @@ case "$1" in
shift
;;
*)
# address and netmask as two separate arguments
str2ip ipaddr "$1" || exit 1
str2ip netmask "$2" || exit 1
shift 2
;;
esac
# we either have no arguments left, or we have a range start and length
if [ $# -ne 0 ] && [ $# -ne 2 ]; then
usage
fi
@ -74,6 +80,7 @@ fi
hostmask=$((netmask ^ 0xffffffff))
network=$((ipaddr & netmask))
broadcast=$((network | hostmask))
count=$((hostmask + 1))
_ip2str IP "$ipaddr"
_ip2str NETMASK "$netmask"
@ -81,13 +88,16 @@ _ip2str NETWORK "$network"
echo "IP=$IP"
echo "NETMASK=$NETMASK"
# don't include this-network or broadcast addresses
if [ "$prefix" -le 30 ]; then
_ip2str BROADCAST "$broadcast"
echo "BROADCAST=$BROADCAST"
fi
echo "NETWORK=$NETWORK"
echo "PREFIX=$prefix"
echo "COUNT=$count"
# if there's no range, we're done
[ $# -eq 0 ] && exit 0
if [ "$prefix" -le 30 ]; then

View File

@ -1,5 +1,7 @@
uint_max=4294967295
# check that $1 is only base 10 digits, and that it doesn't
# exceed 2^32-1
assert_uint32() {
local __n="$1"
@ -21,6 +23,7 @@ assert_uint32() {
return 0
}
# return a count of the number of bits set in $1
bitcount() {
local __var="$1" __c="$2"
assert_uint32 "$__c" || return 1
@ -35,6 +38,8 @@ bitcount() {
}
# tedious but portable with busybox's limited shell
# we check each octet to be in the range of 0..255,
# and also make sure there's no extaneous characters.
str2ip() {
local __var="$1" __ip="$2" __n __val=0
@ -131,6 +136,7 @@ str2ip() {
return 0
}
# convert back from an integer to dotted-quad.
ip2str() {
local __var="$1" __n="$2"
assert_uint32 "$__n" || return 1