How to determine if you have an internet connection in R

后端 未结 9 963
南旧
南旧 2020-11-30 01:16

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.

相关标签:
9条回答
  • 2020-11-30 01:49

    This is a version of eyjo's answer which sacrifices accuracy for speed.

    IPavailable <- function() {
      cmd <- switch(.Platform$OS.type, "windows" = "ipconfig", "ifconfig")
      any(grep("(\\d+(\\.|$)){4}", system(cmd, intern = TRUE)))
    }
    
    0 讨论(0)
  • 2020-11-30 01:50

    Just another one to add to the pot, inspired by @romans answer, this works only on Windows I'd assume, not sure about other platforms:

    canPingSite <- function(test.site) {
        !as.logical(system(paste("ping", test.site)))
    }
    

    Which we test as follows:

    > t1 <- canPingSite("www.yahoo.com")
    [...]
    
    > t2 <- canPingSite(";lkjsdflakjdlfhasdfhsad;fs;adjfsdlk")
    [...]
    
    > t1; t2
    [1] TRUE
    [1] FALSE
    
    0 讨论(0)
  • 2020-11-30 01:56

    All these answers use packages or code outside of base R. Here's how to do it with just base 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)
    }
    
    0 讨论(0)
提交回复
热议问题