#!/bin/perl
#Send a UDP datagram to the daytime server on another host.
#Display the UDP datagram that comes back.

use Socket;

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

$name = 'aixmita1.urz.uni-heidelberg.de';
$ip = inet_aton($name) or die "$0: couldn't get IP address for \"$name\"";

socket(S, AF_INET, SOCK_DGRAM, 0) or die "$0: $!";
$n = send(S, '', 0, sockaddr_in($port, $ip));
defined $n or die "$0: $!";
if ($n != 0) {
	die "$0: sent $n bytes instead of 0 bytes\n";
}

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

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

$address = recv(S, $buffer, 100, 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 {
	die "$0: The datagram I was waiting for didn't arrive in 15 seconds.\n";
}
