TCP Port checking script

D

darkmoo

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
#
# Author: Ralf Schwarz <[email protected]>
# 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{ALRM} = 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;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,968
Messages
2,570,154
Members
46,702
Latest member
LukasConde

Latest Threads

Top