http://qs321.pair.com?node_id=25634

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

I have this:
$SIG{"ALRM"} = sub {close(SOCKET); }; alarm '5'; socket(SOCKET, PF_INET, SOCK_STREAM, getprotobyname('tcp')); $iaddr = inet_aton($host); $paddr = sockaddr_in($myport, $iaddr); if (connect(SOCKET, $paddr)) { $SIG{"ALRM"} = sub { close(SOCKET); &outage($host); exit(0); }; alarm '5'; socket(TS, PF_INET, SOCK_STREAM, getprotobyname('tcp')); $paddrr = sockaddr_in($myport, $iaddr); connect(TS, $paddrr); recv (TS, $buff, $responselength, ''); if ($buff eq $myresponse) { &do9094stuff($host,$region); exit(0); } else { #print "$host: Hung Port Detected!\n"; close(SOCKET); &outage($host); exit(0); } } else { &outage($host); }
I know that the distinguishing needs to be done in that last else, but I have no idea where to start..

Originally posted as a Categorized Question.

Replies are listed 'Best First'.
Re: How can I distinguish between 'Connection refused' and 'Connection timed out?'
by tye (Sage) on Aug 02, 2000 at 07:34 UTC

    $!, of course. If you use Errno qw(ECONNREFUSED ETIMEDOUT); then you can do:

    if( $! == ECONNREFUSED() ) { ...connection was refused... } elsif( $! == ETIMEDOUT() ) { ...connection timed out... } else { ...some other error... }

    Under Win32, connect() is a "winsock" call, not an operating system call, so it doesn't set errno. However, the glue code inside perl.exe that calls connect() copies the value from WSAGetLastError() into errno.

    Unfortunately, this doesn't work all that well. For example, "$!" will show as "", making you think that 0==$!. Also, the above code won't work since the error codes are not ECONNREFUSED and ETIMEDOUT but WSAECONNREFUSED and WSAETIMEDOUT so the code that builds the Errno module doesn't know to make those available.

    So, if you want your code to port to Win32, you can add something like:

    BEGIN { if( $^O =~ /Win32/i ) { eval ' sub() ECONNREFUSED { 10061; } sub() ETIMEDOUT { 10060; } 1;' or die $@; } }