Perl
  Home arrow Perl arrow Page 3 - Programming Sockets with PERL
Dev Shed Forums 
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Forums Sitemap 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
VPS Hosting 
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
Google.com  
PERL

Programming Sockets with PERL
By: Rahul Chauhan
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 55
    2004-04-21


    Table of Contents:
  • Programming Sockets with PERL
  • Types of Sockets
  • Client–Server Script in PERL
  • PERL Makes Life Easy
  • Conclusion

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article

     
     
    ADVERTISEMENT


    Programming Sockets with PERL - Client–Server Script in PERL
    (Page 3 of 5 )

    Comfortable so far? Let's dive head-first in to coding a simple client server interaction in PERL. Client/server network programming requires a server running on one machine to serve one or more clients running on either the same machine or different machines. These different machines can be located anywhere on the network.

    To create a server, simply perform the following steps using the built-in Perl function indicated:
    1. Create a socket with socket.
    2. Bind the socket to a port address with bind.
    3. Listen to the socket at the port address with listen.
    4. Accept client connections with accept.
    Establishing a client is even easier:
    1. Create a socket with socket.
    2. Connect (the socket) to the remote machine with connect.
    A Simple Server

    1. #! /usr/bin/perl -w
    2. # server0.pl
    3. #--------------------

    4. use strict;
    5. use Socket;

    6. # use port 7890 as default
    7. my $port = shift || 7890;
    8. my $proto = getprotobyname('tcp');

    9. # create a socket, make it reusable
    10. socket(SERVER, PF_INET, SOCK_STREAM, $proto) or die "socket: $!";
    11. setsockopt(SERVER, SOL_SOCKET, SO_REUSEADDR, 1) or die "setsock: $!";

    12. # grab a port on this machine
    13. my $paddr = sockaddr_in($port, INADDR_ANY);

    14. # bind to a port, then listen
    15. bind(SERVER, $paddr) or die "bind: $!";
    16. listen(SERVER, SOMAXCONN) or die "listen: $!";
    17. print "SERVER started on port $port ";

    18. # accepting a connection
    19. my $client_addr;
    20. while ($client_addr = accept(CLIENT, SERVER))
    21. {
    22. # find out who connected
    23. my ($client_port, $client_ip) = sockaddr_in($client_addr);
    24. my $client_ipnum = inet_ntoa($client_ip);
    25. my $client_host = gethostbyaddr($client_ip, AF_INET);
    26. # print who has connected
    27. print "got a connection from: $client_host","[$client_ipnum] ";
    28. # send them a message, close connection
    29. print CLIENT "Smile from the server";
    30. close CLIENT;
    31. }


    Analysis

    This simple server can run just on one machine that can service only one client program at a time connecting from the same or a different machine. Recall that the steps for creating a server were to create a socket, bind it to a port, listen at the port and accept client connections.

    Line 1 and 4
    It is generally a good idea to compile a Perl script using strict. This requires all variables to be declared with the "my" function before they are used. Using "my" may be inconvenient, but it can catch many common syntactically correct yet logically incorrect programming bugs.

    Line 7
    The variable $port is assigned the first command-line argument or port 7890 as the default. When choosing a port for your server, pick one that is unused on your machine.

    Line 10 and 11
    The socket is created using the socket function. A socket is like a file handle-it can be read from, written to or both. The function setsockopt is called to ensure that the port will be immediately reusable.

    Line 13
    The sockaddr_in function obtains a port on the server. The argument INADDR_ANY chooses one of the server's virtual IP addresses. You could instead decide to bind only one of the virtual IP addresses by replacing INADDR_ANY with inet_aton("192.168.1.1") or gethostbyname ('localhost')

    Line 15
    The bind function binds the socket to the port, i.e., plugs the socket into that port.

    Line 16
    The listen function causes the server to begin listening at the port. The second argument to the listen function is the maximum queue length or the maximum number of pending client connections. The value SOMAXCONN is the maximum queue length for the machine being used.

    Line 20
    Once the server begins listening at the port, it can accept client connections using the accept function. When the client is accepted, a new socket is created named CLIENT which can be used like a file handle. Reading from the socket reads the client's output and printing to the socket sends data to the client. The return value of the accept function is the Internet address of the client in a packed format.

    Line 24 and 25
    The function sockaddr_in takes the packed format and returns the client's port number and the client's numeric Internet address in a packed format. The packed numeric Internet address can be converted to a text string representing the numeric IP using inet_ntoa (numeric to ASCII). To convert the packed numeric address to a host name, the function gethostbyaddr is used.

    Start the script on a localhost. I ran these scripts on a Windows 2000 machine with Active PERL ( binary build 631 PERL v5.6.1). The output looks something like this.

    D:GalantPerl>start server1.pl
    SERVER started on port 7890


    The server is now listening at port 7890 on the local host, waiting for clients to connect.

    A Simple Client

    1. #! /usr/bin/perl -w
    2. # client1.pl - a simple client
    3. #----------------

    4. use strict;
    5. use Socket;

    6. # initialize host and port
    7. my $host = shift || 'localhost';
    8. my $port = shift || 7890;

    9. my $proto = getprotobyname('tcp');

    10. # get the port address
    11. my $iaddr = inet_aton($host);
    12. my $paddr = sockaddr_in($port, $iaddr);
    13. # create the socket, connect to the port
    14. socket(SOCKET, PF_INET, SOCK_STREAM, $proto)
    a. or die "socket: $!";
    15. connect(SOCKET, $paddr) or die "connect: $!";

    16. my $line;
    17. while ($line = )
    18. {
    19. print $line;
    20. }
    21. close SOCKET or die "close: $!";


    Analysis

    Line 7 and 8
    Takes the command-line arguments of host name and port number or if no arguments are passed initializes variables with the default values.

    Line 11 and 12
    The host name and the port number are used to generate the port address using inet_aton (ASCII to numeric) and sockaddr_in.

    Line 14 and 15
    A socket is created using socket and the client connects the socket to the port address using connect.

    Line 17 and 21
    The while loop then reads the data the server sends to the client until the end-of-file is reached, printing this input to STDOUT. Then the socket is closed.

    Output on the server:

    D:GalantPerl>start server1.pl
    SERVER started on port 7890
    got a connection from: SHILPA[172.16.0.160]


    Output on the client:

    C:> ahulperlclient1.pl rahul
    Smile from the server


     
     
    >>> More Perl Articles          >>> More By Rahul Chauhan
     

       

    PERL ARTICLES

    - More Perl Bits
    - Perl, Bit by Bit
    - Basic Charting with Perl
    - Using Getopt::Long: More Command Line Option...
    - Command Line Options in Perl: Using Getopt::...
    - Web Access with LWP
    - More Templating Tools for Perl
    - Site Layout with Perl Templating Tools
    - Build a Perl RSS Aggregator with Templating ...
    - Looping, Security, and Templating Tools
    - Perl: Bon Voyage Lists and Hashes
    - Templating Tools
    - Perl: Number Crunching
    - Perl Debuggers in Detail
    - Debugging Perl



     



    © 2003-2010 by Developer Shed. All rights reserved. DS Cluster 1 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek