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

I have been using the following code in linux to check for hosts with port 80 open. It works fine in linux. In windows, however, the connection attempt does not timout. When there is no response, it ignores the alarm completely and takes about 20 seconds to bomb out. I have tried many different things but cannot get any socket connection attempts to timeout in windows. Any help would be appreciated =)

Best Regards!

smack
use IO::Socket; use IO::Scalar; my $port = 80; print "Please enter an IP: "; my $ip = <STDIN>; print "\nTrying $ip"; my $TIMEOUT = 3; # seconds eval { local $SIG{ALRM} = sub { die "alarm\n" }; alarm $TIMEOUT; &CheckHost($ip, $port); alarm 0; }; if ($@) { if($@ eq "alarm\n") { die "Connection Timed out.\n"; } else { print "Socket Closed.\n"; } } sub CheckHost() { ($hostip, $hostport) = ($_[0], $_[1]); my $sock = new IO::Socket::INET ( PeerAddr => "$hostip", PeerPort => "$hostport", Proto => 'tcp', ); die "Could not create socket: $!\n" unless $sock; chomp $hostport; print "Port $hostport is active on $hostip\n"; close($sock); }

Replies are listed 'Best First'.
Re: Windows socket timout code
by mifflin (Curate) on Sep 03, 2004 at 19:07 UTC
    I haven't tried this myself but the perldoc on IO::Socket::INET mentions a parameter on the constructor...
    Timeout Timeout value for various operations
    If you haven't already, try adding it to your connect...
    my $sock = new IO::Socket::INET ( PeerAddr => "$hostip", PeerPort => "$hostport", Proto => 'tcp', Timeout => $TIMEOUT, );
      I did try that already... several times even. Can't get it to work. I read up on this a bit as well. It seems a lot of people have trouble getting any timeout method to work on sockets in windows. I have read that the alarm function is limited in windows.... maybe it just can't work with sockets? For now I am using Net::Ping to make sure the host exists first, but that is really ineffecient. Maybe I should use a module of some sort?

      Thanx for your reply =)

      smack
      another accidental posting, deleted =)
      accidental posting, deleted =)