#!BOURNESHELL
#	program:	netmask
#	purpose:	Figure out the actual netmask for the given IP address
#			(host or network) by looking for Subnet "A" RRs in
#			the in-addr.arpa. domain hierarchy.  This algorithm
#			comes from RFC1101 section 4.4.  If the domain database
#			does not include RFC1101 enhancements, this tool will
#			always return the default netmask according to what
#			class the network belongs (A, B, C, ...)
#	input:		IP address in normal format ("134.114.64.2").
#	output:		network mask address record if any found,
#			or the word "ERROR".
#	exit value:	0 if succeeds, 1 if fails (and "ERROR" output).

if test $# -ne 1; then
	echo "usage: $0 ipaddress" >&2
	echo 'ERROR'
	exit 1
fi

if test "`DOMBIN/type $1`" != "forward"; then
	echo "$0: argument $1 is not an IP address." >&2
	echo 'ERROR'
	exit 1
fi

addr="`DOMBIN/netwithzeros $1`"
if test x"$d" = x"ERROR"; then
	echo "$0: netwithzeros failed to work on $1 IP address." >&2
	echo 'ERROR'
	exit 1
fi

# Start by applying the default netmask for the network.
mask="`DOMBIN/addr2mask $addr`"
if test x"$d" = x"ERROR"; then
	echo "$0: addr2mask failed to work on $addr IP address." >&2
	echo 'ERROR'
	exit 1
fi

# Potentially infinite levels of sub-sub-networks.
while true; do
	# Figure out the subnetwork address.
	net="`DOMBIN/addr2net $addr $mask`"
	if test x"$d" = x"ERROR"; then
		echo "$0: addr2net failed to work on $addr address with $mask subnetmask." >&2
		echo 'ERROR'
		exit 1
	fi

	# Force network number into in-addr format.
	d="`DOMBIN/f2iaddr $net`"
	if test x"$d" = x"ERROR"; then
		echo "$0: f2iaddr failed to work on $net network address." >&2
		echo 'ERROR'
		exit 1
	fi

	# Do an "A" RR query to get netmask record, ala RFC 1101.
	oldmask="$mask"
	mask="`DOMBIN/address $d 2> /dev/null`"
	if test $? -ne 0; then
		break
	fi
	# If mask looked up is the default for this network, avoid infinite-loop!
	if test x"$mask" = x"$oldmask"; then
		break
	fi
done

echo "$oldmask"
exit 0
