Marco Marco - 1 year ago 94
R Question

Ping a website in R

I would like to create a script in R that pings a given website. I haven't found any information about this specific for R.

To start with, all I need is the information on whether the website responses to the ping or not.

Does anyone have information about existing scripts or which package best to use to start with?

Answer Source

We can use a system2 call to get the return status of the ping command in the shell. On Windows (and probably linux) following will work :

ping <- function(x, stderr = FALSE, stdout = FALSE, ...){
    pingvec <- system2("ping", x,
                       stderr = FALSE,
                       stdout = FALSE,...)
    if (pingvec == 0) TRUE else FALSE

# example
> ping("")
> ping("")
[1] TRUE

If you want to capture the output of ping, you can either set stdout = "", or use a system call:

> X <- system("ping", intern = TRUE)
> X
 [1] ""                                                         "Pinging [] with 32 bytes of data:" 
 [3] "Reply from bytes=32 time<1ms TTL=62"       "Reply from bytes=32 time<1ms TTL=62"      
 [5] "Reply from bytes=32 time<1ms TTL=62"       "Reply from bytes=32 time<1ms TTL=62"      
 [7] ""                                                         "Ping statistics for"                      
 [9] "    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss)," "Approximate round trip times in milli-seconds:"          
[11] "    Minimum = 0ms, Maximum = 0ms, Average = 0ms"         

using the option intern = TRUE makes it possible to save the output in a vector. I leave it to the reader as an exercise to rearrange this in order to get some decent output.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download