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

Consider the following Perl script fragment:

use IO::Socket; # ... my $sock = IO::Socket::INET->new( PeerAddr => $host, # eg "google.com" PeerPort => $port, # eg 80 Proto => 'tcp' ); die("no socket: $!") unless $sock; # ... 

Everything works as expected under normal conditions, but when the host’s Internet connection is inactive, the sock variable is empty and $! has the message "Invalid argument".

Am I using the INET constructor improperly or is this the expected behavior? If the latter, is there a way to distinguish between an "inactive" network interface and a true invalid argument for the constructor method?

+4
source share
1 answer

You see "Invalid argument" because the constructor is trying to resolve the host name, receives an error message, and returns EINVAL in $! . If you use the IP address in $host , you will see a real error: "Network is unavailable."

In addition, IO::Socket::INET sets up $@ 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 diagnosis than the "Network is unavailable", which you will receive with an IP address instead of a host name. In both cases, it should be immediately clear what is happening.

+8
source

All Articles