codescracker


perl

Perl Socket Programming



« Previous Tutorial Next Tutorial »


Basically a socket is a mechanism of creating a virtual duplex connection between the different processes. Using socket programming with perl, a typical computer system on a network receives and sends the information as desired by the various applications that are running on it. This information is routed to the system, since a unique IP address designed to it. On the system, this information is given to the relevant applications, listen on the different ports.

Creating a Server

Here are the steps to create a server:

Creating a Client

Here are the steps to create a client:

Perl Socket Programming Example

Here is a perl program for the implementation of a simple client-server program using the perl socket. Here is the perl script to create a server. This is server.pl file:

#!/usr/bin/perl -w

use strict;
use Socket;

my $port = shift || 7890;
my $proto = getprotobyname('tcp');
my $server = "localhost";

socket(SOCKET, PF_INET, SOCK_STREAM, $proto)
   or die "Can't open the socket $!\n";
setsockopt(SOCKET, SOL_SOCKET, SO_REUSEADDR, 1)
   or die "Can't set the socket option to the SO_REUSEADDR $!\n";

bind( SOCKET, pack_sockaddr_in($port, inet_aton($server)))
   or die "Can't bind to the port $port! \n";

listen(SOCKET, 5) or die "listen: $!";
print "SERVER started on the port $port\n";

my $client_addr;
while ($client_addr = accept(NEW_SOCKET, SOCKET))
{
   my $name = gethostbyaddr($client_addr, AF_INET );
   print NEW_SOCKET "Smile from the server";
   print "Connection received from the $name\n";
   close NEW_SOCKET;
}

To run the server in background mode the type the following command on the Unix prompt/terminal:

$perl sever.pl&

Now, here is the perl script to create a client. This is client.pl file:

!/usr/bin/perl -w

use strict;
use Socket;

my $host = shift || 'localhost';
my $port = shift || 7890;
my $server = "localhost";

socket(SOCKET,PF_INET,SOCK_STREAM,(getprotobyname('tcp'))[2])
   or die "Can't create a socket $!\n";
   
connect( SOCKET, pack_sockaddr_in($port, inet_aton($server)))
   or die "Can't connect to the port $port! \n";

my $line;
while($line = <SOCKET>)
{
        print "$line\n";
}
close SOCKET or die "close: $!";

Now, you can start your client at the command prompt, which will connect to the server and read the message sent by the server and displays the same on the screen like this:

$perl client.pl
Smile from the server

« Previous Tutorial Next Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test