Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Allo all, I am attempting to check if certain specified ports are listening via TCP... This is how i check.. I notice that if the IP is not up, then the socket call will keep trying for "EVER" .. even with the eval ALARM set... What else can I do to timeout the socket connection event?
sub opensock { my $addr = $_[0]; my $port = $_[1]; my $sock; my $status = 0; $SIG{ALRM} = sub {die "$port timed out\n"}; eval { alarm(2); $sock = new IO::Socket::INET ( PeerAddr => $addr, PeerPort => $port, Proto => 'tcp', undef ); alarm (0); }; if ($sock) { $status=1; close($sock); } undef $sock; return $status; }

Replies are listed 'Best First'.
Re: IO::Socket Connection Timeout lasts forever
by growlf (Pilgrim) on Mar 19, 2002 at 23:54 UTC

    According to PerlDoc, you can specify the following:

        PeerAddr	Remote host address          <hostname>[:<port>]
        PeerHost	Synonym for PeerAddr
        PeerPort	Remote port or service       <service>[(<no>)] | <no>
        LocalAddr	Local host bind	address      hostname[:port]
        LocalHost	Synonym for LocalAddr
        LocalPort	Local host bind	port         <service>[(<no>)] | <no>
        Proto	Protocol name (or number)    "tcp" | "udp" | ...
        Type	Socket type                  SOCK_STREAM | SOCK_DGRAM | ...
        Listen	Queue size for listen
        ReuseAddr	Set SO_REUSEADDR before binding
        Reuse	Set SO_REUSEADDR before binding (deprecated, prefer ReuseAddr)
        ReusePort	Set SO_REUSEPORT before binding
     -->Timeout	Timeout	value for various operations
        MultiHomed  Try all adresses for multi-homed hosts  
     
    Have you tried specifying the timeout?

    *G*

    Edited by footpad, ~Wed Mar 20 04:31:35 2002 (GMT)