Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

perl listen to a port number to check status

Tags:

port

perl

I have a daemon, for which, I need to check the status and see if it is up or down. As of now, I am using an expect script to telnet to the port and see if it is alive. I am looking to rewrite it in perl, to check the same. Any pointers to modules or features that I can use is greatly appreciated.

like image 434
file2cable Avatar asked Nov 07 '25 11:11

file2cable


2 Answers

http://metacpan.org/pod/IO::Socket::PortState would be a good place to start. There might be better solutions, but this is what I am using.

like image 98
nohup Avatar answered Nov 10 '25 09:11

nohup


For quickly checking a single port, Net::EmptyPort provides check_port, or it's simple enough to do it yourself with IO::Socket::IP. Both are less hassle than using IO::Socket::PortState for just one port (which describes its own interface as “complex”).

With Net::EmptyPort:

use Net::EmptyPort qw<check_port>;

if (check_port 5432)
{
    # ...
}

But if you look at what that's doing, you may decide you can as easily make the socket connection yourself, along the lines of:

use IO::Socket::IP;

my $socket = IO::Socket::IP->new(PeerAddr => 'localhost', PeerPort => 5432);
if ($socket)
{
  $socket->close;
  # ...
}

That also lets you provide other arguments, such as Timeout to adjust how long it waits before giving up and deciding that the port isn't in use. For localhost you may be able to get away with a much shorter time-out than the default; I've used 100 ms without problem.

like image 41
Smylers Avatar answered Nov 10 '25 10:11

Smylers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!