#!/bin/perl
#Output the numbers of the TCP ports we were able to open on the given host.
#The argument is the hostname or IP address of the given host,
#e.g., i5.nyu.edu or 128.122.253.152

use Socket;

if (@ARGV != 1) {
	die "$0: requires one argument";
}

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

$SIG{ALRM} = 'handle_sigalrm';

for ($port = 0; $port < 1024; ++$port) {
	if ($port % 1000 == 0) {
		print "port $port\n";
	}

	$address = sockaddr_in($port, $ip) or die "$0: sockaddr_in failed";
	socket(S, AF_INET, SOCK_STREAM, 0) or die "$0: $!";
	alarm(15);

	if (connect(S, $address)) {
		print "$hostname $port";
		$servername = getservbyport($port, 'tcp');
		if (defined $servername) {
			print " $servername";
		}
		print "\n";
		shutdown(S, SHUT_RDWR) or die "$0: $!";
	}
}

sub handle_sigalrm {
}

exit 0;
