mattp341 has asked for the wisdom of the Perl Monks concerning the following question:

I am brand spanking new to Perl and this is my first script ever, please go easy on me. So this is my code here:

#Author: Matt Pawlaczyk #Date: 1-6-2017 #Desc: This script takes in a URL and continuosly pings it. The IP e +quivalent of the hostname is returned # and a message displays to indicate if it is online or not. use strict; use warnings; use 5.010; use Socket; use Net::Ping; #acquire a host to ping from the user print "Enter a website to ping:\n"; my $input = <STDIN>; chomp $input; #get the IP address for the hostname my $address = inet_ntoa(inet_aton($input)); #a ping object is created, the protocol by default is TCP, changed to +icmp my $p = Net::Ping->new("icmp"); #ping the inputted website to see if it is live or not. (we do this 10 + times) print "Attempting to ping $input.....\n"; for(my $i = 1; $i <= 10; $i = $i++){ if ($p->ping($input)) { print "Response from $address succesful\n"; #delay execution by 1 second sleep(1); } else { return undef; print "No response from server, try again.\n"; } } print "Done.";
When I enter in for example, "google.com" It works, the ping is successful and I get the IP for the hostname - life is good. However, when I enter in an invalid URL, I get an error message that I am having trouble making sense of. It says to me:
Use of uninitialized value in subroutine entry at pingTest.pl line 16, + <STDIN> line 1. Bad arg length for Socket::inet_ntoa, length is 0, should be 4 at ping +Test.pl line 16, <STDIN> line 1.
Can anybody help me? I've been searching for about an hour now and cannot come up with an answer to this problem.

Replies are listed 'Best First'.
Re: Getting what I seem to believe are error with inet_ntoa(inet_aton())
by stevieb (Canon) on Jan 06, 2017 at 20:46 UTC

    Welcome to the Monastery, mattp341!

    What's happening is you're receiving an undefined/null value from inet_aton() when you mistype a hostname, and that's what inet_ntoa() is complaining about.

    You should check the return from inet_aton() before sending it into inet_ntoa(). Here's a very rough example. It'll ask the user for a hostname until inet_aton() returns something useful:

    my $addr; while (! $addr){ print "enter a damned FQDN: "; my $input = <STDIN>; chomp $input; $addr = inet_aton($input); } my $ip = inet_ntoa($addr);

    You could also just terminate the application if a hostname is mistyped instead of looping and re-asking for input:

    my $addr = inet_aton($input); die "invalid hostname specified\n" if ! $addr; my $ip = inet_ntoa($addr); ...

      Thanks so much I got it working!