Home arrow Perl Programming arrow Page 3 - Programming Sockets with PERL

Client–Server Script in PERL&toc - Perl

In this article, Rahul shows us how to create a client-server socket program in Perl and then demonstrates it by pinging the server.

TABLE OF CONTENTS:
  1. Programming Sockets with PERL
  2. Types of Sockets
  3. Client–Server Script in PERL
  4. PERL Makes Life Easy
  5. Conclusion
By: Rahul Chauhan
Rating: starstarstarstarstar / 57
April 21, 2004

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement
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 Programming Articles          >>> More By Rahul Chauhan
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PERL PROGRAMMING ARTICLES

- Perl Turns 25
- Lists and Arguments in Perl
- Variables and Arguments in Perl
- Understanding Scope and Packages in Perl
- Arguments and Return Values in Perl
- Invoking Perl Subroutines and Functions
- Subroutines and Functions in Perl
- Perl Basics: Writing and Debugging Programs
- Structure and Statements in Perl
- First Steps in Perl
- Completing Regular Expression Basics
- Modifiers, Boundaries, and Regular Expressio...
- Quantifiers and Other Regular Expression Bas...
- Parsing and Regular Expression Basics
- Hash Functions

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: