在R中Ping一个网站 [英] Ping a website in R

查看:100
本文介绍了在R中Ping一个网站的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在R中创建一个可对给定网站执行ping操作的脚本.我还没有找到有关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.

首先,我需要提供的信息是有关网站是否响应ping的信息.

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?

推荐答案

我们可以使用system2调用来获取Shell中ping命令的返回状态.在Windows(可能是linux)上,以下方法将起作用:

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("google.com")
[1] FALSE
> ping("ugent.be")
[1] TRUE

如果要捕获ping的输出,则可以设置stdout = ""或使用系统调用:

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

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

使用选项intern = TRUE可以将输出保存为向量.我把它留给读者作为练习,以重新安排它,以获得一些体面的输出.

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.

这篇关于在R中Ping一个网站的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆