Perl Socket Programming

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:

  • Firstly, create a socket using the socket call
  • Now, bind the socket to a port address using the bind call
  • Then, listen to the socket at the port address using the listen call
  • And now, accept the client connections using the accept call

Creating a Client

Here are the steps to create a client:

  • Firstly, create a socket with the socket call
  • And then, connect to the server using the connect call

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 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";
   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:


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

!/usr/bin/perl -w

use strict;
use Socket;

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

   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:

Smile from the server

Perl Online Test

« Previous Tutorial Next Tutorial »

Like/Share Us on Facebook 😋