Hello all,
I have created a Perl script that tries to open connections to various systems on different ports in order to see if the machines are reachable, the ports are open, etc.
There appears to be a difference between Solaris (10) and Linux (RH/Oracle and Ubuntu) in the status or error it throws. On Solaris I get expected results when I check $! after opening and connecting a socket, and I have a simple routine to catch messages like 'Connection timed out', 'Connection refused', etc.
On Linux, however, both the creation of the socket and the connect statements deliver an 'Illegal seek' status via $! for servers/ports that respond.
The question first revolves around whether I have taken an incorrect approach in order to retrieve and use the status of the connection, but secondly also about error handling.
The many examples available on the internet almost always use the 'die' statement when creating or connecting a socket - not a very neat way to handle exceptions. I haven't seen many alternative means of catching exceptions and dealing with them effectively.
The code:
use strict;
use IO::Socket;
use vars qw($configfile @listen @filter @unknown @nlisten @pingable);
sub test_connect {
my ($srvproto, $host, $port) = @_;
# print "$srvproto\t$host\t$port\n";
# get the port address
my $iaddr = inet_aton($host);
if (defined $iaddr) {
my $paddr = sockaddr_in($port, $iaddr);
my $proto = getprotobyname($srvproto);
# create the socket, connect to the port
socket(MYSOCK, PF_INET, SOCK_STREAM, $proto)|| die "Failed: $!\n";
connect(MYSOCK, $paddr);
my $sockstat=$!;
if ($sockstat eq "") {
@listen=(@listen, [$srvproto, $host, $port]);
}
elsif ($sockstat eq "Connection timed out") {
@filter=(@filter, [$srvproto, $host, $port]);
}
elsif ($sockstat eq "Connection refused") {
@nlisten=(@nlisten, [$srvproto, $host, $port]);
}
elsif ($sockstat eq "Illegal seek") {
@listen=(@listen, [$srvproto, $host, $port]);
}
else {
print $sockstat . "\n";
}
close MYSOCK or die "close: $!";
} else {
@unknown=(@unknown, [$srvproto, $host, $port]);
}
}
You can see I have created an 'elsif' statement for the 'Illegal seek' message, which wasn't necessary on Solaris.
Any help or advice on how to 1. change the script to act accordingly, and 2. how to generally implement these types of exception handling, are very very much welcome.
Many thanks, kind regards.