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

#!/fellow/monks.pl

I have the following procedure that I use to determine if a TCP port is available. When it's up, it works fine, however, I found that when a link goes down, it takes a while to timeout, resulting in my script to sit and wait a long time before continuing. Is there any way I can force a timeout?

use IO::Socket; sub check_port { my ($host,$port) = @_; $remote = IO::Socket::INET -> new ( Proto => "tcp", PeerAddr => $host, PeerPort => $port ) ; if ($remote) { close $remote; return 1; } else { return 0; } }

Thanks!

#!/massyn.pl The early worm gets caught by the bird.

Replies are listed 'Best First'.
Re: TCP port check time out?
by bronto (Priest) on Mar 12, 2003 at 10:31 UTC

    Use perldoc IO::Socket:

    timeout([VAL]) Set or get the timeout value associated with this socket. If called without any arguments then the cur- rent setting is returned. If called with an argument the current setting is changed and the previous value returned.

    Ciao!
    --bronto


    The very nature of Perl to be like natural language--inconsistant and full of dwim and special cases--makes it impossible to know it all without simply memorizing the documentation (which is not complete or totally correct anyway).
    --John M. Dlugosz
Re: TCP port check time out?
by Tomte (Priest) on Mar 12, 2003 at 10:34 UTC

    First go for brontos tip.
    If that doesn't help/suit your needs, take a look at perldoc -f alarm and in perldoc perlvar search for %SIG

    regards,
    tomte


    Edit:I received downvotes for this node
    I'd like a cb-/msg or an answer on why.
    A quick glance, before I wrote this node, into IO/Socket.pm suggested that the timeout is implemented, as it should be, using the correct calls to the underlying OS, and not a brute-force approach like alarm. I wrote this tip, because there are circumstances where a socket timeout may just not work (mostly OS related, me thinks), but alarm will.