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

socket(S, AF_INET, SOCK_DGRAM, 0) or die "$0: $!";

sub IPPROTO_IP {return 0;}   #IPv4
sub IP_TTL     {return 4;}   #IPv4 time to live

setsockopt(S, IPPROTO_IP, IP_TTL, 10) or die "$0, $!";
$ttl = getsockopt(S, IPPROTO_IP, IP_TTL) or die "$0, $!";
$t = unpack('I', $ttl);
print "The time to live was set to $t.\n";

$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";

$address = sockaddr_in($port, $ip);
$n = send(S, '', 0, $address);
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 UDP 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 {
	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";
}
