문제

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top