#!/bin/perl
#Send a UDP datagram with the specified number of bytes of cargo
#to an echo server.  Display the UDP datagram that comes back.

use Socket;

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

$name = $ARGV[0];
$size = $ARGV[1];

$ip = inet_aton($name) or die "$0: couldn't get IP address for $name";

$port = getservbyname('echo', 'udp')
	or die "$0: couldn't find udp service daytime";

socket(S, AF_INET, SOCK_DGRAM, 0) or die "$0: $!";
$address = sockaddr_in($port, $ip);

$n = send(S, 'A' x $size, 0, $address);
defined $n or die "$0: $!";
if ($n != $size) {
	die "$0: sent $n bytes instead of $size bytes\n";
}

$address = getsockname(S) or die "$0: $!";   #Can't do this before the send.
($port, $ip) = sockaddr_in($address);
print "I sent a datagram from my port $port.\n";

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

$address = recv(S, $buffer, $size, 0) or die "$0: $!";
($port, $ip) = sockaddr_in($address);

print "I then received a datagram containing the following ", length($buffer),
	" bytes\nfrom port $port of ", inet_ntoa($ip);

$name = gethostbyaddr($ip, AF_INET);
if (defined $name) {
	print " ($name)";
}

print "\n$buffer\n";
exit 0;

sub handle_sigalrm {
	if ($_[0] ne 'ALRM') {
		die "$0: received signal $_[0] instead of ALRM";
	}
	die "$0: The datagram I was waiting for didn't arrive in 15 seconds.\n";
}
