Occasionally it's good to know if a server is up and functioning. The echo service is used to make that determination. The code in serverup.pl shows how one checks the upness of two servers.
Caution Windows 95 (and perhaps other operating systems) can't use the SIGALRM interrupt signal. This might cause problems if you use this script on those systems because the program will wait forever when a server does not respond.
serverup.pl operates as follows:
The Perl code for serverup.pl is:
#!/usr/bin/perl -w use Socket; use strict; print "miles.planet.net is up.\n" if echo('miles.planet.net'); print "sentinel.planet.net is up.\n" if echo('sentinel.planet.net'); sub echo { my($host) = shift; my($timeout) = shift || 5; my($oldAlarmHandler, $status); my($proto) = getprotobyname("tcp") || 6; my($port) = getservbyname("echo", "tcp") || 7; my($serverAddr) = (gethostbyname($host))[4]; return(print("echo: $host could not be found, sorry.\n"), 0) if ! defined($serverAddr); if (0 == Win32::IsWin95) { $oldAlarmHandler = $SIG{'ALRM'}; $SIG{'ALRM'} = sub { die(); }; alarm($timeout); } $status = 1; # assume the connection will work. socket(ECHO, AF_INET(), SOCK_STREAM(), $proto) or die("socket: $!"); $packFormat = 'S n a4 x8'; # Windows 95, SunOs 4.1+ #$packFormat = 'S n c4 x8'; # SunOs 5.4+ (Solaris 2) connect(ECHO, pack($packFormat, AF_INET(), $port, $serverAddr)) or $status = 0; close(ECHO); if (0 == Win32::IsWin95) { alarm(0); $SIG{'ALRM'} = $oldAlarmHandler; } return($status); }
This program will display:
echo: miles.cs.cf.ac.uk could not be found, sorry. sentinel.cs.cf.ac.uk is up.
When dealing with the echo service, you only need to make the connection in order to determine that the server is up and running. As soon as the connection is made, you can close the socket.
Most of the program should be pretty familiar to you by now. However, you might not immediately realize what return statement in the middle of the echo() function does. The return statement is repeated here:
return(print("echo: $host could not be found, sorry.\n"), 0) if ! defined($serverAddr);
The statement uses the comma operator to execute two statements where normally you would see one. The last statement to be evaluated is the value for the series of statements. In this case, a zero value is returned.
The return statement could also be done written like this:
if (! defined($serverAddr) { print("echo: $host could not be found, sorry.\n") return(0); }