Click here to get back home

TCP Port checking script

 HomeNewsGroups | Search | About
 comp.lang.perl.misc    Post an article   get this group's latest topics as an RSS feed add this group's latest topics to your My MSN content add this group's latest topics to your My Yahoo content
Subject Author Date
TCP Port checking script darkmoo 08-25-2006
Posted by darkmoo on August 25, 2006, 4:44 am
Please log in for more thread options
I have borrowed a script that checks to see if a tcp port is openned. If
not I want it to restart a service. I can stop the service but not sure
how to check the running state of the service before starting it. I've
dont something simple like sleep but I get am error. SIGALARM or something
like that.

Thanks for the help (:


#!/usr/bin/perl -w
#
# February 20th 2006
#
# returns 0 if host is listening on specified tcp port
#

use strict;
use Socket;

# set time until connection attempt times out
my $timeout = 3;

if ($#ARGV != 1) {
print "usage: is_tcp_port_listening hostname portnumber\n";
exit 2;
}

my $hostname = $ARGV[0];
my $portnumber = $ARGV[1];
my $host = shift || $hostname;
my $port = shift || $portnumber;
my $proto = getprotobyname('tcp');
my $iaddr = inet_aton($host);
my $paddr = sockaddr_in($port, $iaddr);

socket(SOCKET, PF_INET, SOCK_STREAM, $proto) || die "socket: $!";

eval {
local $SIG = sub { die "timeout" };
alarm($timeout);
connect(SOCKET, $paddr) || error();
alarm(0);
};

if ($@) {
close SOCKET || die "close: $!";
print "$hostname is NOT listening on tcp port $portnumber.\n";
system("net","stop","SSH Tunnel");
sleep 5;
system("net","start","SSH Tunnel");
exit 1;
}
else {
close SOCKET || die "close: $!";
print "$hostname is listening on tcp port $portnumber.\n";
exit 0;
}



Similar ThreadsPosted
Socket Send and Receive, Same local port, Different Remote Port March 1, 2005, 12:35 pm
perl script to interact with PC port April 23, 2008, 10:13 am
Serial Port programming - Reading DSR from port July 11, 2005, 2:29 pm
com port June 10, 2005, 9:49 am
port 80 January 3, 2006, 7:28 pm
POE and Port Redirection September 17, 2004, 9:29 pm
OS/2 port of Perl 5.8 not adding CR to \n August 29, 2004, 2:06 pm
wildcard the port in bind January 18, 2005, 3:27 am
XP Serial port control December 30, 2005, 8:55 pm
two servers listening on same port ? June 19, 2006, 4:17 pm

Our other projects:

Art Dolls, Fairies and Mermaids - Sunnyfaces.net

Roy's Linux, Programming and Search Engines messages

1-Script XML SitemapXML Sitemap