如何确定您是否在R中有互联网连接

Cla*_*ton 35 r

有时我需要从互联网上下载数据.有时因为网站关闭或我的电脑丢失了互联网连接而导致失败.

问题:R中是否有一些函数会返回TRUE/FALSE我是否连接到互联网?

Rom*_*rik 26

一个肮脏的工作将使用RCurl::getURL功能.

if (is.character(getURL("www.google.com"))) {
    out <- TRUE
} else {
    out <- FALSE
}
Run Code Online (Sandbox Code Playgroud)

  • 可缩短为:`out < - is.character(getURL("www.google.com"))` (14认同)
  • 实际上当没有网络getURL发出错误时,你应该使用`out <-try(is.character(getURL("www.google.com")))== TRUE` (2认同)
  • 请参阅下面的答案,了解`curl`包中更优雅的解决方案. (2认同)

Jer*_*oen 22

curl软件包具有has_internet通过执行以下操作进行测试的功能nslookup:

curl::has_internet
## function(){
##    !is.null(nslookup("google.com", error = FALSE))
## }
Run Code Online (Sandbox Code Playgroud)

测试DNS比检索URL更可靠,因为后者可能由于无关原因(例如防火墙,服务器关闭等)而失败.


eyj*_*yjo 16

这是尝试解析ipconfig/ifconfig的输出,正如Spacedman所建议的那样.

havingIP <- function() {
  if (.Platform$OS.type == "windows") {
    ipmessage <- system("ipconfig", intern = TRUE)
  } else {
    ipmessage <- system("ifconfig", intern = TRUE)
  }
  validIP <- "((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)[.]){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"
  any(grep(validIP, ipmessage))
}
Run Code Online (Sandbox Code Playgroud)

使用简单的TRUE/FALSE输出

> havingIP()
[1] TRUE
Run Code Online (Sandbox Code Playgroud)

  • 至少在我的计算机(基于Linux 3.13的Mint)上,当没有互联网连接时,它可以返回TRUE。 (2认同)
  • 这不会检查您是否有活动的互联网连接。它检查您是否具有有效的IP地址。我刚刚关闭了wifi,仍然返回TRUE。 (2认同)

Ton*_*yal 10

只有另一个添加到底池,受@romans答案的启发,这只适用于Windows我假设,不确定其他平台:

canPingSite <- function(test.site) {
    !as.logical(system(paste("ping", test.site)))
}
Run Code Online (Sandbox Code Playgroud)

我们测试如下:

> t1 <- canPingSite("www.yahoo.com")
[...]

> t2 <- canPingSite(";lkjsdflakjdlfhasdfhsad;fs;adjfsdlk")
[...]

> t1; t2
[1] TRUE
[1] FALSE
Run Code Online (Sandbox Code Playgroud)

  • 我得到了两个downvotes,但我无法解释为什么?我不关心声望点(它们对我来说毫无意义),但我想了解这个解决方案的坏处.我对downvotes的推理是因为这个解决方案只适用于windows,我觉得这很公平:) (3认同)

Zek*_*eke 7

所有这些答案都使用基本 R 之外的包或代码。以下是仅使用基本 R 执行此操作的方法:

# IANA's test website
is_online <- function(site="http://example.com/") {
  tryCatch({
    readLines(site,n=1)
    TRUE
  },
  warning = function(w) invokeRestart("muffleWarning"),
  error = function(e) FALSE)
}
Run Code Online (Sandbox Code Playgroud)


TPA*_*row 6

只需两行代码即可完成:

install.packages('pingr')
pingr::is_online()
Run Code Online (Sandbox Code Playgroud)

  • 事实上,您不需要第 2 行。 (2认同)

Eri*_*ric 5

Bioconductor的Biobase软件包具有测试Internet连接的功能。

Biobase::testBioCConnection()
Run Code Online (Sandbox Code Playgroud)

下面是此功能的重大修改版本,用于测试从URL读取行的功能。

can_internet <- function(url = "http://www.google.com") {

    # test the http capabilities of the current R build
    if (!capabilities(what = "http/ftp")) return(FALSE)

    # test connection by trying to read first line of url
    test <- try(suppressWarnings(readLines(url, n = 1)), silent = TRUE)

    # return FALSE if test inherits 'try-error' class
    !inherits(test, "try-error")
}

can_internet()
Run Code Online (Sandbox Code Playgroud)