#!/bin/perl
#Output the IP address and fully qualified domain name of every host
#on the same network as the given host.
#The first argument is the hostname or IP address of a given host,
#e.g., i5.nyu.edu or 128.122.253.152
#The second argument is the number of network bits in the netmask, e.g., 26

use Socket;

if (@ARGV != 2) {
        die "$0: requires 2 arguments";
}

$hostname = $ARGV[0];
$netbits  = $ARGV[1];   #number of network bits in the bitmask

if ($netbits <= 0 || $netbits > 30) {
	die "$0: netbits $netbits must be in range 1 to 30 inclusive";
}

$ip = inet_aton($hostname)
        or die "$0: argument $hostname must be a hostname or dotted IP address";

$i = unpack('N', $ip);

$hostbits = 32 - $netbits;

#The netmask is $netbits 1's, followed by $hostbits 0's.
$netmask = -1 << $hostbits;

#The network address is the IP address, with all the host bits turned off.
$network = $i & $netmask;

#The broadcast address is the IP address, with all the host bits turned on.
$broadcast = $i | ~$netmask;

for ($i = $network + 1; $i < $broadcast; ++$i) {
	$ip = pack('N', $i);
	$name = gethostbyaddr($ip, AF_INET);
	if (defined $name) {
		print inet_ntoa($ip), " $name\n";
	}
}

exit 0;
