Sometimes I need to download data from the internet. On occasions this has failed either because the website is down or because my computer has lost its internet connection.
The curl
package has a function has_internet
which tests by performing a nslookup
:
curl::has_internet
## function(){
## !is.null(nslookup("google.com", error = FALSE))
## }
Testing DNS is faster and may be more reliable than retrieving a URL because the latter might fail for unrelated reasons (e.g. firewall, server down, etc).
Do it with just two lines of code:
install.packages('pingr')
pingr::is_online()
As the function above from eyjo
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))
}
also returns true for localhost ip "127.0.0.1" it needs to be removed to prevent false positives. For example as shown below:
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[-grep("127.0.0.1", ipmessage)]))
}
But even better would be a solution that prevents localhosts by modifying the regex of validIP.
A dirty work around would be using RCurl::getURL
function.
if (is.character(getURL("www.google.com"))) {
out <- TRUE
} else {
out <- FALSE
}
Here is an attempt at parsing the output from ipconfig/ifconfig, as suggested by 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))
}
With a simple TRUE/FALSE output
> havingIP()
[1] TRUE
Bioconductor's Biobase package has a function for testing internet connection.
Biobase::testBioCConnection()
Below is a heavily modified version of this function for testing ability to read lines from a 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()