Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl IO::Socket::INET confusing "Invalid argument" error

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?

like image 570
maerics Avatar asked Feb 25 '23 02:02

maerics


1 Answers

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.

like image 89
Grrrr Avatar answered Mar 04 '23 04:03

Grrrr