#!BOURNESHELL
#	program:	network
#	purpose:	Figure out the actual network of the given IP address
#			by looking for Subnet "A" RRs in the in-addr.arpa.
#			domain hierarchy and applying the netmask to the
#			address passed in.  This algorithm comes from RFC1101
#			section 4.4.  If the domain database does not include
#			RFC1101 enhancements (what ashame!), this tool will
#			always return the default network according to what
#			class the IP address belongs (A, B, C, ...)
#	input:		IP address in normal format ("134.114.64.2").
#	output:		Network IP address zero-filled to have 4 octets,
#			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

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 "$net"
exit 0
