How To: Perl TCP / UDP Socket Programming using IO::Socket::INET

by Balakrishnan Mariyappan on July 1, 2010

In this article, let us discuss how to write Perl socket programming using the inbuilt socket modules in Perl.

Perl socket modules provides an object interface that makes it easier to create and use TCP / UPD sockets.

This article covers the following topics:

  • Perl example code for TCP client and server
  • Perl example code for UDP client and server
  • Read and write descriptor list using Select(IO::Select)

CPAN module IO::Socket::INET is used to perform socket operations such as — creating, binding, connecting, listening and closing the socket.

IO::Select module is used for obtaining the descriptors that are ready for read/write operations.

Perl TCP Client and Server

TCP is a connection oriented networking protocol. In this example, let us review the Perl code-snippet that will explaining us the simple client and server communication.

Perl TCP Server Operation

The socket operation such as socket creation, binding and listening to the socket is performed by the IO::Socket::INET module.

The Perl code given below does the following:

  • Create the Socket
  • Bind the socket to an address and port
  • Listen to the socket at the port address
  • Accept the client connections
  • Perform read/write operation on the socket.
#!/usr/bin/perl
#tcpserver.pl

use IO::Socket::INET;

# flush after every write
$| = 1;

my ($socket,$client_socket);
my ($peeraddress,$peerport);

# creating object interface of IO::Socket::INET modules which internally does 
# socket creation, binding and listening at the specified port address.
$socket = new IO::Socket::INET (
LocalHost => '127.0.0.1',
LocalPort => '5000',
Proto => 'tcp',
Listen => 5,
Reuse => 1
) or die "ERROR in Socket Creation : $!\n”;

print "SERVER Waiting for client connection on port 5000";

while(1)
{
# waiting for new client connection.
$client_socket = $socket->accept();

# get the host and port number of newly connected client.
$peer_address = $client_socket->peerhost();
$peer_port = $client_socket->peerport();

print “Accepted New Client Connection From : $peeraddress, $peerport\n ”;

# write operation on the newly accepted client.
$data = “DATA from Server”;
print $client_socket “$data\n”;
# we can also send the data through IO::Socket::INET module,
# $client_socket->send($data);

# read operation on the newly accepted client
$data = <$client_socket>;
# we can also read from socket through recv()  in IO::Socket::INET
# $client_socket->recv($data,1024);
print “Received from Client : $data\n”;
}

$socket->close();

Also, refer to our earlier Perl debugger article to learn how to debug your perl code.

Perl TCP Client Operation

The Perl code given below does the following:

  • Create the socket.
  • Connect to the remote machine at a specific port.
  • Perform read/write operation on the socket.
#!/usr/bin/perl
#tcpclient.pl

use IO::Socket::INET;

# flush after every write
$| = 1;

my ($socket,$client_socket);

# creating object interface of IO::Socket::INET modules which internally creates 
# socket, binds and connects to the TCP server running on the specific port.
$socket = new IO::Socket::INET (
PeerHost => '127.0.0.1',
PeerPort => '5000',
Proto => 'tcp',
) or die "ERROR in Socket Creation : $!\n”;

print “TCP Connection Success.\n”;

# read the socket data sent by server.
$data = <$socket>;
# we can also read from socket through recv()  in IO::Socket::INET
# $socket->recv($data,1024);
print “Received from Server : $data\n”;

# write on the socket to server.
$data = “DATA from Client”;
print $socket “$data\n”;
# we can also send the data through IO::Socket::INET module,
# $socket->send($data);

sleep (10);
$socket->close();

Note: You can use Vim editor as a Perl IDE using the perl-support.vim Plugin.

Perl UDP Server

The Perl code given below does the following:

  • Create the socket.
  • Bind the socket to the specific port.
#!/usr/bin/perl
#udpserver.pl

use IO::Socket::INET;

# flush after every write
$| = 1;

my ($socket,$received_data);
my ($peeraddress,$peerport);

#  we call IO::Socket::INET->new() to create the UDP Socket and bound 
# to specific port number mentioned in LocalPort and there is no need to provide 
# LocalAddr explicitly as in TCPServer.
$socket = new IO::Socket::INET (
LocalPort => '5000',
Proto => 'udp',
) or die "ERROR in Socket Creation : $!\n”;

while(1)
{
# read operation on the socket
$socket->recv($recieved_data,1024);

#get the peerhost and peerport at which the recent data received.
$peer_address = $socket->peerhost();
$peer_port = $socket->peerport();
print "\n($peer_address , $peer_port) said : $recieved_data";

#send the data to the client at which the read/write operations done recently.
$data = “data from server\n”;
print $socket “$data”;

}

$socket->close();

Perl UDP Client

The Perl code given below does the following:

  • Create the UDP client.
  • Connect to the specific UDP server.
  • Perform write and read operation on the socket.
#!/usr/bin/perl
#udpclient.pl

use IO::Socket::INET;

# flush after every write
$| = 1;

my ($socket,$data);

#  We call IO::Socket::INET->new() to create the UDP Socket 
# and bind with the PeerAddr.
$socket = new IO::Socket::INET (
PeerAddr   => '127.0.0.1:5000',
Proto        => 'udp'
) or die "ERROR in Socket Creation : $!\n”;
#send operation
$data = “data from client”;
$socket->send($data);

#read operation
$data = <$socket>;
print “Data received from socket : $data\n ”;

sleep(10);
$socket->close();

Also, refer to our earlier article to understand Perl Array Reference.

IO::Select Module – Get to know the list of ready descriptors

IO::Select module provides following two major functions:

  • can_read() returns the available read descriptors
  • can_write() returns the available write descriptors

To understand the usage of IO::Select, we are going to use this module in the tcpserver code.

Step 1 : Create the IO::Socket object interface

The following code-snippet creates the object interface of IO::Socket::INET modules which internally creates a socket, binds and listens to a specified port address.

$socket = new IO::Socket::INET (
LocalHost => '127.0.0.1',
LocalPort => '5000',
Proto => 'tcp',
Listen => 5,
Reuse => 1
) or die "ERROR in Socket Creation : $!\n";

$select = IO::Select->new($socket) or die "IO::Select $!";

Step 2 : Add descriptors to Select objects

The following code-snippet adds the descriptor to the list of select objects to get the descriptors ready.

@ready_clients = $select->can_read(0);
foreach my $fh (@ready_clients)  {
print $fh "";
if($fh == $socket)       {
my $new = $socket->accept();
$select->add($new);
}
}

Step 3: Get descriptors which are ready to read

Following Perl code-snippets gets the list of descriptor that are ready to read.

@ready_clients = $select->can_read(0);
foreach my $fh (@ready_clients)  {
if($fh != $socket)  {
chomp($data=<$socket>);
print $data,"\n";
}
}

In the same way, we can do for the write operation on the socket.

Step 4: Remove Client Socket Descriptor from Select list

When the connection is closed, you can remove the client socket descriptor for the select slit as shown below.

SIGPIPE signal gets generated when we try to send/receive data on the socket that is closed by the remote machine. So, we can assign the signal handler for SIGPIPE signal, which should remove of descriptor from the select list as shown below.

# $current_client is the global variable which has the recent file descriptor 
# on which the send/receive operation is tried.
### Handle the PIPE
$SIG{PIPE} =  sub
{
####If we receieved SIGPIPE signal then call Disconnect this client function
print "Received SIGPIPE , removing a client..\n";
unless(defined $current_client){
print "No clients to remove!\n";
}else{
$Select->remove($current_client);
$current_client->close;
}
#print Dumper $Self->Select->handles;
print "Total connected clients =>".(($Select->count)-1)."<\n";
};

Linux Sysadmin Course Linux provides several powerful administrative tools and utilities which will help you to manage your systems effectively. If you don’t know what these tools are and how to use them, you could be spending lot of time trying to perform even the basic administrative tasks. The focus of this course is to help you understand system administration tools, which will help you to become an effective Linux system administrator.
Get the Linux Sysadmin Course Now!

If you enjoyed this article, you might also like..

  1. 50 Linux Sysadmin Tutorials
  2. 50 Most Frequently Used Linux Commands (With Examples)
  3. Top 25 Best Linux Performance Monitoring and Debugging Tools
  4. Mommy, I found it! – 15 Practical Linux Find Command Examples
  5. Linux 101 Hacks 2nd Edition eBook Linux 101 Hacks Book

Bash 101 Hacks Book Sed and Awk 101 Hacks Book Nagios Core 3 Book Vim 101 Hacks Book

{ 8 comments… read them below or add one }

1 cra July 2, 2010 at 4:39 am

the code has some troubles – the part with
or die “ERROR in Socket Creation : $!\n”;
uses wrong quotation marks (unmatched)

2 cra July 2, 2010 at 4:40 am

… and your parser in comments fixed my unmatched quotation mark. :)

3 Jamz July 5, 2010 at 5:07 pm

How can i monitor the IO Socket ?

My socket is constantly sending queries to a remote server (every millisecond)

I need to know if the socket is causing problems (i.e. dropping packets or buffering)

Great article , please write more :)

Keep up the good working !

4 Andrew September 15, 2010 at 5:47 pm

Please get rid of the “smart” quotes in your code samples.

5 Vinod Halaharvi March 22, 2011 at 2:53 pm

#Ability to connect the server to multiple ports and multiple clients on each port

use warnings;
use IO::Socket::INET;
use IO::Select;

# flush after every write
$| = 1;

my ($socket,$client_socket);
my ($peeraddress,$peerport);
# creating object interface of IO::Socket::INET modules which internally does
# socket creation, binding and listening at the specified port address.
$numArgs = $#ARGV + 1;

# for each port on the command line for a new server socket,
# one server socket per port
foreach $argnum (0 .. $#ARGV) {
my ($port) = $ARGV[$argnum];

#duplicate this program
my($pid) = fork();
if ( $pid != 0 ) {
#parent process
print “parent\n”;
print “Done with parent..\n”;
}
else {
#child process
$lsn = new IO::Socket::INET (
LocalHost => ’127.0.0.1′,
LocalPort => $port,
Proto => ‘tcp’,
Listen => 1,
Reuse => 1
);

print “Child\n”;
my($file_name) = “server.output”;
open my $log, ‘>>’, $file_name
or die “$0 : failed to open output file ‘$file_name’ : $!\n”;

$sel = new IO::Select( $lsn );
print “SERVER Waiting for client connection on port “. $port. “\n”;
while(@ready = $sel->can_read) {
foreach $fh (@ready) {
if($fh == $lsn) {
# Create a new socket
my($new) = $lsn->accept;
print “Connect client: “. $new->sockaddr() . ” port: ” . $port . “\n”;
$sel->add($new);
}
else {
# Process socket
# Maybe we have finished with the socket
my($remote_address) = $fh->recv($data,1024);
print $remote_address. “:” . $port .”:”. $data;
}
}
} #while
close ($log)
or warn “$0 : failed to close output file ‘$file_name’ : $!\n”;
#return ;
$socket->close();
} # else
} #for

6 Sam August 26, 2011 at 7:05 am

In your server code there is a typo
You allocate two variables
$peer_address = $client_socket->peerhost();
$peer_port = $client_socket->peerport();

But then use the wrong names (peeraddress/port instead of peer_address/port)
print “Accepted New Client Connection From : $peeraddress, $peerport\n ”;

The use of strict would have caught this.

7 Pete March 19, 2013 at 4:20 am

Notice the variance in how received is spelt. In udpserver.pl

The declaration is correct spelling
my ($socket,$received_data);
The use isn’t
$socket->recv($recieved_data,1024);

Not that it stops anything from working,

8 Surendhar M July 22, 2014 at 12:59 am

It was useful for me. This site will cover all the things about sockets in perl simply and superb.

Leave a Comment

Previous post:

Next post: