问题描述
测试您的互联网是否连接到 R
中的 wifi 或以太网的最可靠方法是什么?
我想做一个 if
语句,例如:
if (internet == "wifi") {
return(x)
} else if (internet == "ethernet") {
return(y)
} else { #no internet
return(z)}
system("ipconfig",intern = T)
似乎很有用,但我不确定要提取什么,以便无论连接设置如何,每次都能正确识别 wifi/以太网。
我在 windows
环境中工作。
谢谢
解决方法
我的代码不是最漂亮的,但它会返回一个数据框,您可以在其中简单地根据“状态”和“接口名称”列读取连接状态。主要问题是您最终可能会遇到各种以太网/WiFi 配置,因此解析 ipconfigs 输出非常复杂。
我的版本基于简单的 shell 命令 netsh interface show interface
代码如下:
netsh_lst = system("netsh interface show interface",intern = T)
netsh_df <- NULL
for (i in seq(1,length(netsh_lst))){
current_line <- as.vector(strsplit(netsh_lst[i],'\\s+')[[1]])
if (length(current_line)>4){
current_line <- current_line[1:3]
current_line[4] <- paste(current_line[4:length(current_line)],collapse = ' ')
}
if (length(current_line)>2){
netsh_df = rbind(netsh_df,current_line)
}
}
names <- netsh_df[1,]
colnames(netsh_df) <- names
netsh_df <- netsh_df[-1,]
row.names(netsh_df) <- 1:length(netsh_df[,1])
print(netsh_df)