Sunday, July 25, 2010

Perl - How to create a tcp socket?

The following program can be used to create a tcp connection to a host on a specified port.
The program attempts connection at a periodic interval, which is passed as 'execution_interval'.

#!/usr/bin/perl
use IO::Socket;
use POSIX qw/strftime/;
if (@ARGV != 4)
{
  usage(); 
  exit;              
}
my $hostname = $ARGV[0];
my $port = $ARGV[1];
my $timeout = $ARGV[2];
my $interval = $ARGV[3];

my $logdir = "/tmp/";
my $datestamp = strftime('%m-%d-%y_%H:%M:%S',localtime);
$mday = (localtime(time))[3];

my $logfile = $logdir."$hostname\_$port\_tcp_socket\_$datestamp.log";
open LOG, ">>","$logfile" or die $!;
LOG->autoflush(1);
while(1) {
    my $sock = new IO::Socket::INET (PeerAddr => $hostname,
                                     PeerPort => $port,
                                     Proto => 'tcp',
                                     Timeout => $timeout);
    $cur_datestamp = strftime('%m-%d-%y_%H:%M:%S',localtime);
    $cur_mday = (localtime(time))[3];   
    if(!$sock) {
        print LOG "\n$cur_datestamp : Error - Could not create socket to $hostname on $port: $!";
        sleep $interval;
        next;       
    }   
    if($cur_mday != $mday) {
        close(LOG);
        $logfile = $logdir."$hostname\_$port\_tcp_socket\_$datestamp.log";
        open LOG, ">>","$logfile" or die $!;
        LOG->autoflush(1);
        $mday = $cur_mday;
    }   
   
    print LOG "\n$cur_datestamp : Socket created to $hostname on $port";   
    close($sock);
    sleep $interval;
}

close(LOG);

sub usage
{
  print "Invalid parameters \nUsage: ./tcp_socket.pl \n";
}



Please let me know, of any corrections/improvements.

No comments: