#!/bin/sh
#	program:	subnetmask
#	release:	1.5.0
#	purpose:	Fetch the netmask RR from the name server.  This is
#			an RFC1101 idea, which is officially optional but
#			is the ONLY way to determine the true subnet mask
#			of a network!
#	input:		network address in normal format ("134.114.64"),
#			optional nameserver to direct queries to.
#	output:		network mask address record if any found,
#			or the word "ERROR" (distinguishable from a real
#			record because it has no period on the end).
#	exit value:	0 if succeeds, 1 if fails (and "ERROR" output).
#
# Copyright (C) 1993-2000 Paul A. Balyoz <pab@domtools.com>
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#

if test $# -lt 1 -o $# -gt 2; then
	echo "usage: $0 [@nameserver] net-IP-addr" >&2
	echo 'ERROR'
	exit 1
fi

ip=
nameservers=
atnameserver=
while test $# -gt 0; do
        case "$1" in
                @*)  atnameserver="$1" nameservers=`echo $1 | sed -e 's/@//'` ;;
                *)  ip="$1" ;;
        esac
        shift
done
if test x"$ip" = x""; then
        echo "$0: No IP address specified; aborting." >&2
        echo "usage: $0 [@nameserver] net-IP-addr" >&2
        echo 'ERROR'
        exit 1
fi

# Force network number into host-zero, in-addr format.
addr="`/usr/local/domtools/bin/netwithzeros $ip`"
if test x"$addr" = x"ERROR"; then
	echo "$0: netwithzeros failed to work on $ip network address." >&2
	echo 'ERROR'
	exit 1
fi

# Convert address to in-addr domain name
net="`/usr/local/domtools/bin/f2iaddr $addr`"

# Do an "A" RR query to get netmask record, ala RFC 1101.
subnetmask="`/usr/local/domtools/bin/address $atnameserver $net 2> /dev/null`"
if test $? -ne 0; then
	echo "$0: no subnetmask record found ala RFC 1101."
	echo 'ERROR'
	exit 1
fi

echo "$subnetmask"
exit 0
