#!/bin/perl
#The same program, in perl.
use Socket;

$n = 5;   #number of bytes to send and receive
socket(S, AF_INET, SOCK_DGRAM, 0) or die "$0: $!";

$i = send(S, 'Hello', 0, sockaddr_in(7, inet_aton('labinfu.unipv.it')));
defined $i or die "$0: $!";

if ($i != $n) {
	die "$0: only $i bytes were sent; should have been $n.\n";
}

$address = getsockname(S);
defined $address or die "$0: $!";

($port, $ip) = sockaddr_in($address);   #ephemeral port number
print "My port number is $port.  (I am the client.)\n";

print `/bin/netstat -a -f inet -P udp | awk '2 <= NR && NR <= 4 || \$1 ~ /\\.$port/'`;

$SIG{ALRM} = 'handle_sigalrm';
alarm(15);

$address = recv(S, $buffer, 5, 0);
defined $address or die "$0: $!";
$i = length($buffer);

if ($i != $n) {
	die "$0: only $i bytes received; should have been $n.\n";
}

($port, $ip) = sockaddr_in($address);
print "I received a datagram containing the ", length($buffer),
	" bytes \"$buffer\"\n",
	"from port $port of ", inet_ntoa($ip), ".\n";
exit 0;

sub handle_sigalrm {
	print "The datagram I was waiting for never arrived.\n";
	exit 1;
}
