#!/afs/athena/contrib/perl/p

%srvc = (80, "WWW",
	 8001, "WWW8001");

$|=1;
open(HOSTS, "/afs/athena/astaff/reference/hosts/hosts");

while(<HOSTS>){
    ($garbage, $ipaddr, $hostname, $machine, $os, $garbage) = split(/ ?: ?/, $_);
    $ipaddr=~/18\.(\d\d\d)\.(\d+\.\d+)/;
    $subnet = $1;  $last = $2;
    next if $last eq "0.252" || $last eq "0.0" || $last eq "0.1";
    
    next if($os eq "EXEC" || $os eq "BOOT" || $os eq "SNMP"); # || $os eq 
    next if($hostname =~ /TESTER-/);
	
#	print("$hostnames in $lg running $os\n");
#    print("$hostname at $lg\n") if $os=~/LINUX/;
    ($hname, @garbage) = split(/,/, $hostname);
    $procs++;
    $opid = fork();
    if(!$opid){
	&checkservices($hname);
	exit;
    }
    if($procs > 10){
	for $i (1..5){
	    wait;
	    $procs--;
	}
    }
    $opsys{$os}++;
    $where{$lg}++;
    if($lg =~ /Dorm/){
	$dorms++;
    }
    else{
	$ilg++;
    }
    $tot++;
}

sub checkservices {
    local($h) = @_;

    for $port (keys srvc){
	print("Checking $srvc{$port} on $h\n");
	&checkaservice($h, $port);
    }
}

sub checkaservice {
    local($them, $port) = @_;

    $AF_INET = 2;
    $SOCK_STREAM = 1;
    
    $sockaddr = 'S n a4 x8';
    
    chop($hostname = `hostname`);
    
    ($name,$aliases,$proto) = getprotobyname('tcp');
    ($name,$aliases,$port) = getservbyname($port,'tcp')
	unless $port =~ /^\d+$/;;
    ($name,$aliases,$type,$len,$thisaddr) =
        gethostbyname($hostname);
    ($name,$aliases,$type,$len,$thataddr) = gethostbyname($them);
    
    $this = pack($sockaddr, $AF_INET, 0, $thisaddr);
    $that = pack($sockaddr, $AF_INET, $port, $thataddr);
    # Make the socket filehandle.
 
    if (socket(S, $AF_INET, $SOCK_STREAM, $proto)) { 
#	print("...socket...");
    }
    else {
	print("OOps, socket failed\n");
    }
    
# Give the socket an address.

    if (bind(S, $this)) {
#	print("...bind...\n");
    }
    else {
	print("Oops, bind failed\n");
    }
    
# Call up the server.
    $pid = fork();
    if(!$pid){
	alarm(10);
	if (connect(S,$that)) {
	    print("*****Found $srvc{$port} running on $them in $lg\n");
	}
	
	close(S);
	exit(0);
    }
    wait;
}


