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

($port) = @ARGV;
$port = 2345 unless $port;

$AF_INET = 2;
$SOCK_STREAM = 1;

$sockaddr = 'S n a4 x8';

($name, $aliases, $proto) = getprotobyname('tcp');
if ($port !~ /^\d+$/) {
    ($name, $aliases, $port) = getservbyport($port, 'tcp');
}

print "Port = $port\n";

$this = pack($sockaddr, $AF_INET, $port, "\0\0\0\0");

select(NS); $| = 1; select(stdout);

socket(S, $AF_INET, $SOCK_STREAM, $proto) || die "socket: $!";
bind(S,$this) || die "bind: $!";
listen(S,5) || die "connect: $!";

select(S); $| = 1; select(stdout);

$con = 0;
#print "Listening for connection 1....\n";
for(;;) {
    ($addr = accept(NS,S)) || die $!;

    $con++;
    if (($child[$con] = fork()) == 0) {
	print "accept ok\n";

	($af,$port,$inetaddr) = unpack($sockaddr,$addr);
	@inetaddr = unpack('C4',$inetaddr);
#	print "$con: $af $port @inetaddr\n";

	while (<NS>) {
	    $addr = $_;
	    chop($addr);
	    chop($addr);
#	    print(NS "Checking --$addr--\n");
	    ($ip1, $ip2, $ip3, $ip4, $ip5) = gethostbyname($addr);
	    ($ip1, $ip2, $ip3, $ip4) = unpack('C4', $ip5);
	    print(NS "$ip1.$ip2.$ip3.$ip4\n");
	}
	close(NS);
	exit;
    }
    close(NS);

    printf("Listening for connection %d\n",$con+1);
}
