TCP Port checking script

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

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" };
  connect(SOCKET, $paddr) || error();

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;

Site Timeline