CGI Programming on the World Wide WebBy Shishir Gundavaram1st Edition March 1996 This book is out of print, but it has been made available online through the O'Reilly Open Books Project. |
10.4 Socket Library
To make the whole task of creating clients and servers easier, a socket library was developed that encapsulates the various socket and network information functions. Here is the same finger client using the library:
#!/usr/local/bin/perl require "sockets.pl"; $service = "finger"; chop ($hostname = `/bin/hostname`); $input = shift (@ARGV); ($username, $remote_host) = split (/@/, $input, 2); unless ($remote_host) { $remote_host = $hostname; }Most of the code here is the same as that used in the previous example, with one exception. The require command includes the sockets.pl library.
&open_connection (FINGER, $remote_host, $service) || die "Cannot open connection to: $remote_host", "\n";The open_connection library subroutine performs the following tasks:
- Check to see if the remote host is an IP number (128.197.152.10) or an IP name (acs.bu.edu), and perform the appropriate conversion to a packed address string.
- Create a socket.
- Bind the socket to the current host.
- Connect the socket to the remote address and port.
- Unbuffer the socket.
Now, here is the rest of the program.
print FINGER $username, "\n"; while (<FINGER>) { print; } &close_connection (FINGER); exit (0);The close_connection subroutine flushes the socket so that all the remaining information in the socket is released, and then closes it. As you can see, this library makes the whole process of communicating with network servers much easier. Now, let's look at a simple example that interacts with an HTTP server.
Back to: CGI Programming on the World Wide Web
© 1999, O'Reilly & Associates, Inc.