next up previous contents
Next: Sending Mail (SMTP) Up: Some Network Examples Previous: Some Network Examples

Using the Time Service

It is very important that all computers on a given network report the same time. This allows backups and other regularly scheduled events to be automated. Instead of manually adjusting the time on every computer in the network, you can designate a time server. The other computers can use the time server to determine the correct time and adjust their own clocks accordingly.

The code below, time.pl, contains a program that can retrieve the time from any time server in the world.

The basic operation of the code is as follows:

The perl code for time.pl is as follows:

#!/usr/bin/perl  -w


use Socket;
use strict;


my($remoteServer)     = 'time.server.net';


my($secsIn70years)    = 2208988800;
my($buffer)           = '';
my($socketStructure);
my($serverTime);


my($proto)      = getprotobyname('tcp')        || 6;
my($port)       = getservbyname('time', 'tcp') || 37;


my($serverAddr) = (gethostbyname($remoteServer))[4];


printf("%-20s %8s %s\n",  "localhost", 0, ctime(time()));


socket(SOCKET, PF_INET, SOCK_STREAM, $proto)
    or die("socket: $!");


my($packFormat) = 'S n a4 x8';   # Windows 95, SunOs 4.1+
#my($packFormat) = 'S n c4 x8';   # SunOs 5.4+ (Solaris 2)
connect(SOCKET, pack($packFormat, AF_INET(), $port, $serverAddr))
    or die("connect: $!");


read(SOCKET, $buffer, 4);
close(SOCKET);


$serverTime  = unpack("N", $buffer);
$serverTime -= $secsIn70years;


printf("%-20s %8d %s\n", $remoteServer, $serverTime - time,
    ctime($serverTime));


sub ctime {
    return(scalar(localtime($_[0])));
}

Each operating system will have a different method to update the local time. So this needs to configures at your end -- good luck!!


next up previous contents
Next: Sending Mail (SMTP) Up: Some Network Examples Previous: Some Network Examples
dave@cs.cf.ac.uk