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

Hello! I started to use Perl after a half year and I am trying to ping a website. But it not working. I can't ping it, it prints "Not working". When I try with system() it works, but I want to do it with Net::Ping. I also tried with icmp but it prints error, too: "icmp socket error - Bad file descriptor at line 11 " (line 11 is $p = Net::Ping->new('icmp');) what can I do with it? Am I wrong? Or is it a bug?

Thanks for help! My code is:
use Net::Ping; $url = <>; $p = Net::Ping->new(); if ($p->ping($url)) { print "working"; } else {print "not working"; }

Replies are listed 'Best First'.
Re: Net::Ping blowed my mind
by rnewsham (Curate) on Jun 13, 2015 at 21:06 UTC

    Welcome to the monastry, you need to chomp $url to remove the newline from the end of the url.

    It is also highly recommended that you use strict and warnings, believe me it is well worth it.

    Here is a modified version of your script which includes a print before and after a chomp to highlight the difference.

    use strict; use warnings; use Net::Ping; my $url = <>; print ":$url:\n"; chomp($url); print ":$url:\n"; my $p = Net::Ping->new(); if ( $p->ping($url) ) { print "working\n"; } else { print "not working\n"; }
    Output: :www.bbc.co.uk : :www.bbc.co.uk: working
      Thank you so much it worked, I will try to ask harder next time, I am learning java in the school and Perl has some unusual codes for me:)
Re: Net::Ping blowed my mind
by trippledubs (Deacon) on Jun 13, 2015 at 21:19 UTC

    You did not chomp your input, so $url contains a new line if you don't run the script with the url on the command line. If you do run it on the command line, the diamond operator actually is looking for file names. By default Net::Ping attempts to establish a connection to the remote host's echo port via TCP, which may not be what you expect, since normal OS ping is an ICMP ping. If you want this behavior, 'icmp' has to be passed to the Net::Ping constructor.

    So this works:
    #!/usr/bin/env perl use Net::Ping; $url = <>; chomp $url; $p = Net::Ping->new('icmp'); if ($p->ping($url)) { print "working"; } else {print "not working"; }
    ~$ cat text yahoo.com
    And finally the script is ran like this: sudo ./t1.pl text
Re: Net::Ping blowed my mind
by Laurent_R (Canon) on Jun 13, 2015 at 21:02 UTC
    I don't know this module, but maybe you should chomp $url.
Re: Net::Ping blowed my mind
by Anonymous Monk on Jun 14, 2015 at 06:19 UTC
    $url? I think you mean $hostname or $ip not $url :)