#!/usr/local/bin/perl5.00502
#	program:	mask2bits
#	release:	1.5.0
#	input:		one dotted-quad netmask.
#	output:		the number of network bits expressed by the mask
#			to stdout, or "ERROR" to stdout if problem occurs.
#			Usage printed to stderr, too, if usage error occurs.
#	example:	"255.255.255.192" -> "26"
#	exit value:	0 if nothing goes wrong, 1 if something did.
#
# 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.
#

@nth = (
	'1st',
	'2nd',
	'3rd',
	'4th',
);

$chart[0] = 0;
$chart[128] = 1;
$chart[192] = 2;
$chart[224] = 3;
$chart[240] = 4;
$chart[248] = 5;
$chart[252] = 6;
$chart[254] = 7;
$chart[255] = 8;


sub usage {
	print STDERR "usage: $0 netmask\n";
	print "ERROR\n";
	exit 1;
}

&usage  if $#ARGV != 0;			# exactly one arg, or error
&usage  if $ARGV[0] =~ /[^0-9\.]/;	# any non-digits is an error

@p = split(/\./,$ARGV[0]);
&usage  if $#p != 3;			# 4 dotted-quad pieces, or error

$networkpart = 1;		# start by counting network bits
$bits = 0;
for (@p) {
	$i++;
	if (($c = $chart[$_]) eq '') {
		print STDERR "$0: error: non-contiguous netmask bits ($nth[$i-1] octet)\n";
		&usage;
	}
	if ($networkpart && $c != 8) {
		$networkpart = 0;
	} elsif (!$networkpart && $c != 0) {
		print STDERR "$0: error: non-contiguous netmask bits ($nth[$i-1] octet)\n";
		&usage;
	}
	$bits += $c;
}

print "$bits\n";
exit 0;
