home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


12.6 Prebuilt Client Modules

Applications such as mail clients, FTP, web browsers, telnet, and Usenet news-readers are built to use TCP/IP and sockets. Several libraries available on CPAN give you the client-side libraries to roll your own FTP or mail reader, for example, without having to worry about the application protocol. (Note that there are no libraries to write your own servers to handle these protocols.) In this section, we will take a brief look at a couple of interesting client modules packaged under the Net hierarchy and available as libnet from CPAN. These packages were also written by Graham Barr.

12.6.1 Net::FTP

This module implements the client side of the File Transfer Protocol and is used like this:

use Net::FTP;
$ftp = Net::FTP->new("ftp.digital.com");
die "Could not connect: $!" unless $ftp;
$ftp->login('anonymous', 'me@foo.com');  # Guest User; email as passwd
$ftp->cwd('/pub/plan/perl/CPAN');        # cwd:Change Working Directory
$ftp->get('index');
$ftp->quit();

This module supports all the commands that you can issue from a standard FTP program.

As currently implemented, the get call blocks until the entire file is transmitted, so while it is very useful for a batch application (such as mirroring an FTP site nightly), you cannot use it to write a graphical FTP client.

12.6.2 Net::POP3

This library gives an interface to programmatically access a POP (Post Office Protocol) server, used, for example, on dial-up connections. The POP server stores incoming email until the mail reader comes and "visits the post office." Let us study a small example based on Net::POP3.

The trouble with most PC-based mail readers is that they don't give you a preview of the messages and don't wait for you to decide whether you really want to download any of them. People take the Internet's bandwidth for granted all the time, and you might find yourself helplessly waiting as an email containing the latest photograph of Madonna's baby trickles slowly through your dial-up connection. The Perl-based POP client shown below provides a preview of the messages sitting on the POP server: it simply lists the first three lines of all available messages:

use Net::POP3;
$m = Net::POP3->new('pop.myhost.com'); # Name of POP server
die "Could not open account" unless $m;
$n = $m->login('sriram', 'foofoo');    # Login, passwd
print "Number of msgs received: $n\n";
$r_msgs = $m->list();                  # Returns a ref-to-hash mapping 
                                       # msg_id to msg_size
foreach $msg_id (keys %$r_msgs) {
    print "Msg $msg_id (", $r_msgs->{$msg_id}, "):\n";
    print "-----------------\n";
    $rl_msg = $m->top($msg_id, 3);  # Get top three lines from message
    $, = "\n";
    print @$rl_msg;
}
$m->quit();

I use a slightly beefier version of this script to optionally delete messages and then fire up my regular mail reader to download what's left.