Code View: #!/usr/local/bin/perl -Tw
require 5.6.0;
1 use Socket;
use FileHandle;
2 use strict;
3 my($remote, $port, @thataddr, $that,$them, $proto,@now,
$hertime);
# timeclient -- a client for the Time Server program,
# creates a socket and connects it to the server on
# port 29688.
# The client then expects the server to write server's
# host time onto the socket, so the client simply does
# a read on its socket, SOCK, to get the server's time
#
#
# Usage: timeclient [server_host_name]
#
print "Hi, I'm in perl program \'client\' \n";
4 $remote = shift || 'localhost' ;
5 $port = 29688 ; # timeserver is at this port number
6 @thataddr=gethostbyname($remote);
7 $that = pack('Sna4x8', AF_INET, $port, $thataddr[4]);
8 $proto = getprotobyname('tcp');
# Make the socket filehandle
9 if ( socket(SOCK, PF_INET, SOCK_STREAM, $proto ) ){
print "Socket ok.\n";
}
else { die $!; }
# Call up the server
10 if (connect(SOCK, $that)) {
print "Connect ok.\n";
}
else { die $!;}
# Set socket to be command buffered
11 SOCK->autoflush;
# Now we're connected to the server, let's read her host time
12 $hertime = <SOCK>;
13 close(SOCK);
14 print "Server machine time is: $hertime\n";
15 @now = localtime($hertime);
16 print "\tTime-$now[2]:$now[1] ",
"Date-",$now[4]+1,"/$now[3]/$now[5]\n";
(Output)
$ perl timeserver
Port = 29688
Socket ok.
Bind ok.
Listen ok.
In loop.
$ perl timeclient
Hi, I'm in perl program 'client'
Socket ok.
Connect ok.
Server machine time is: 981415699
Time-15:28 Date-2/5/07
The Socket module will be used in this program. The strict pragma is used to ensure that variables used in this program are "safe." These variables will be used later in the program. They must be declared with my because the strict pragma enforces this as a safety feature. A server's hostname may be passed as a command-line argument and shifted into the $port variable. If the ARGV array is empty, the scalar $port is assigned localhost. The client gets the server's port number if it was assigned a value. Now the client gets the server's official address. The raw network address information is obtained by gethostbyname. The address for the server's Internet domain and port number is packed into a binary structure consisting of an unsigned short, a short in "network" order, four ASCII characters, and 8 null bytes. The tcp protocol information is returned. The socket function creates an Internet domain, connection-oriented socket filehandle, SOCK. The connect function connects the client's socket to the server's address. The autoflush method forces the socket's buffers to be flushed after prints and writes. Perl reads from the SOCK filehandle. The server's time is retrieved via the socket. The time value (number of non-leap-year seconds since 1/1/1970, UTC) retrieved from the server is printed. The time is converted to local time and assigned to array @now. The converted time is printed.
|