Consider the following snippet of a Perl script:
use IO::Socket;
# ...
my $sock = IO::Socket::INET->new(
PeerAddr => $host, # e.g. "google.com"
PeerPort => $port, # e.g. 80
Proto => 'tcp'
);
die("no socket: $!") unless $sock;
# ...
Everything works as expected under normal conditions but when then host system's internet connection is inactive the "sock" variable is empty and $!
has the message "Invalid argument".
Am I using the INET constructor inappropriately or is this the expected behavior? If the latter, is there a way to differentiate between a "network interface inactive" error and a genuine invalid argument to the constructor method?
You are seeing "Invalid argument" because the constructor tries to resolve the hostname, gets an error, and returns EINVAL
in $!
. If you would use an IP address in $host
, you would see the real error, "Network is unreachable".
Also, IO::Socket::INET
sets $@
to qualify the error returned in $!
, so if you print $@
as well as $!
, you will see "Bad hostname 'google.com'", which is probably an even better diagnostic than "Network unreachable" you would get with an IP address instead of the hostname. In both cases it should be immediately clear what is going on.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With