O'Reilly logo

Learning Perl, Second Edition by Randal L. Schwartz, Tom Christiansen

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

C.1. A Simple Client

For our simplest client, we'll choose a rather boring service, called "daytime." The daytime server sends a connecting client one line of data containing the time of day on that remote server, then closes the connection.

Here's the client:

#!/usr/bin/perl -w
use IO::Socket;
$remote = IO::Socket::INET->new(
    Proto => "tcp",
    PeerAddr => "localhost",
    PeerPort => "daytime(13)",
    )
    or die "cannot connect to daytime port at localhost";
while ( <$remote> ) { print }

When you run this program, you should get something back that looks like this:

Thu May 8 11:57:15 1997

Here are what those parameters to the new constructor mean:

Proto

The protocol to use. In this case, the socket handle returned will be connected to a TCP socket, because we want a stream-oriented connection, that is, one that acts pretty much like a plain old file. Not all sockets are of this type. For example, the UDP protocol can be used to make a datagram socket, used for message-passing.

PeerAddr

The name or Internet address of the remote host the server is running on. We could have specified a longer name like http://www.perl.com, or an address like http://204.148.40.9. For demonstration purposes, we've used the special hostname localhost, which should always mean the current machine you're running on. The corresponding Internet address for localhost is 127.0.0.1, if you'd rather use that.

PeerPort

This is the service name or port number we'd like to connect to. We could have gotten away with ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required