#!/usr/bin/perl
#   SortHosts [file]..
# Comparison  function  for  IP  addresses  or  any  other   sort   of
# dotted-decimal  notation.   The  original reason for this is to sort
# /etc/hosts, and that's the default. But it will also work for things
# like lists of SNMP OIDs.

sub addr {
	@a = split(/\./, $a);		# Split the number...
	@b = split(/\./, $b); 
	while (@a) {
		next if $a[0] == $b[0];	# and compare the pieces
		return $a[0] - $b[0];
	} continue {
		shift @a; shift @b;
	}
	return 0;
}

#@ARGV = '/etc/hosts' unless (@ARGV); 	# default input is /etc/hosts

# read in hosts file
while (<>) {
	chop;
	next if /^\s*\#/;		# Skip comments
	next unless /\S/;		# Skip blank lines
	($addr, $names) = /(\S+)\s+(.*)/;	
	$names{$addr} = $names;
}

foreach $address (sort addr (keys %names)) { 
	print "$address\t$names{$address}\n"
}
