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.
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()