#!/usr/local/bin/perl5.00502
#                      Address to Network Conversion Utility
#                                by Paul Balyoz
#                                 Release 1.5.0
#
# Input:
#            Full IP Address
#            Network Mask
# Output:
#            Zero-filled Network Address
# Algorithm:
#            Do a Binary-And of the netmask on the address,
#            and print the result to stdout.
# Diagnostics:
#            If wrong number of args: "ERROR" to stdout, info to stderr.
#            If unparsable args: "ERROR" to stdout, info to stderr.
#            Exit value 0 if success, anything else indicates failure.
#
# 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.
#

my(@ipoctets,@maskoctets);
my($ip,$mask,$net);

if ($#ARGV != 1) {
	print STDERR "usage: $0 ipaddress netmask\n";
	print "ERROR\n";
	exit 1;
}

#
# Convert first command-line arg (IP address) to a long integer.
#
@ipoctets = split (/\./,$ARGV[0]);
if ($#ipoctets != 3) {
	print STDERR "$0: ipaddress should be dotted quad, as in 1.2.3.4\n";
	print STDERR "usage: $0 ipaddress netmask\n";
	print "ERROR\n";
	exit 1;
}

#
# Convert second command-line arg (netmask) to a long integer.
#
@maskoctets = split (/\./,$ARGV[1]);
if ($#maskoctets != 3) {
	print STDERR "$0: netmask should be dotted quad, as in 255.255.0.0\n";
	print STDERR "usage: $0 ipaddress netmask\n";
	print "ERROR\n";
	exit 1;
}

#
# Print network which is just IP address with netmask applied to it (bit-ANDed).
#
for ($i=0; $i<4; $i++) {
	$ipoctets[$i] += 0;		# force numeric interpretation
	$maskoctets[$i] += 0;		# force numeric interpretation
	$ipoctets[$i] &= $maskoctets[$i];	# otherwise this masking doesn't work
	print $ipoctets[$i], ($i < 3 ? "." : "\n");
}

exit 0;
