How to determine if you have an internet connection in R

后端 未结 9 1123
南旧
南旧 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:34

    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.

提交回复
热议问题