How to determine if you have an internet connection in R

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


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