Rom*_*rik 26
一个肮脏的工作将使用RCurl::getURL功能.
if (is.character(getURL("www.google.com"))) {
out <- TRUE
} else {
out <- FALSE
}
Run Code Online (Sandbox Code Playgroud)
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)
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)
所有这些答案都使用基本 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)
只需两行代码即可完成:
install.packages('pingr')
pingr::is_online()
Run Code Online (Sandbox Code Playgroud)
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)