当前位置:网站首页>Golang通过exec模块实现Ping连通性检测案例
Golang通过exec模块实现Ping连通性检测案例
2022-04-23 05:32:00 【坐公交也用券】
源码
import (
"fmt"
"os/exec"
"runtime"
)
// 小写函数名称只能在当前文件调用
func pingcmd(host string) bool {
// 实例化一个执行任务
cmds := exec.Command("ping", host)
// 开始执行
err := cmds.Run()
// 判断执行状态(只获取成功或者失败)
if err != nil {
fmt.Println("Connection failed: ", host)
return false
}else {
fmt.Println("Connection successful: ", host)
return true
}
}
// 大写开头的函数可被外部调用
func PingStatus(host string) bool {
// 检测ping是否连接成功
fmt.Println("Pinging ", host)
// 获取当前系统类型
sysType := runtime.GOOS
// 打印当前系统类型
fmt.Println("Current system type: ", sysType)
// 根据系统类型设置对应的参数
if sysType == "windows" {
// Windows 系统下直接使用ping ip
status := pingcmd(host)
return status
}else{
// 非windows下需要使用-c 指定数据包数量
host := host + " -c 5"
status := pingcmd(host)
return status
}
return false
}
func main() {
d := PingStatus("baidu.com")
if d {
fmt.Println("ok")
}else {
fmt.Println("Errors")
}
}
执行结果
Pinging baidu.com
Current system type: windows
Connection successful: baidu.com
ok
版权声明
本文为[坐公交也用券]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_36154886/article/details/124357338
边栏推荐
- catkin_ What did package do
- How to realize adaptive layout
- Various situations of data / component binding
- Data bus realizes the communication between brother components
- Call the interface to get the time
- uni使用的一些坑
- (11) Vscode code formatting configuration
- QT compressed folder
- X86 assembly syntax: at & T and Intel
- 2021-10-25
猜你喜欢
随机推荐
Sword finger offer II 022 The entry node of the link in the linked list
After NPM was upgraded, there was a lot of panic
Intel SGX preliminary learning and understanding notes (continuously updated)
JS time format conversion
MySQL series - install MySQL 5.6.27 on Linux and solve common problems
catkin_ What did package do
what is wifi6?
JSON.
[untitled]
Double click The jar package cannot run the solution
Common interview questions - 4 (MySQL)
2021-09-27
Redis的基本知识
双击.jar包无法运行解决方法
Log introduction and building web application
QT drawpixmap and DrawImage blur problem
Processus d'exécution du programme exécutable
弘玑Cyclone RPA为国金证券提供技术支撑,超200个业务场景实现流程自动化
Note: unordered_ Understanding and use of map
If the route reports an error after deployment according to the framework project






![[untitled]](/img/49/770888f4f351f42af0e01c3a15ddfa.png)
![Laravel [view]](/img/39/71db98d8832d9419bcc1097594d1b6.png)

