当前位置:网站首页>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
边栏推荐
- Necessity of selenium preloading cookies
- 分支与循环语句
- Pavlov and hobbies
- Basic knowledge of redis
- Hongji | how does HR carry out self change and organizational change in the digital era?
- [triangle Yang Hui triangle printing odd even cycle JS for break cycle]
- CMake基础教程(39)pkgconfig
- Formal parameters, local variables and local static variables
- npm升级后问题,慌得一批
- Cross domain CORS relationship~
猜你喜欢

Intel SGX preliminary learning and understanding notes (continuously updated)

QT drawpixmap and DrawImage blur problem

Laravel routing job

Cross domain CORS relationship~

Hongji cyclone RPA provides technical support for Guojin securities and realizes process automation in more than 200 business scenarios

Double click The jar package cannot run the solution

2021-10-25

Requirements for SQL server to retrieve SQL and user information

Box collapse and margin collapse

2021-11-01
随机推荐
Utf8 to STD: string and STD: string to utf8
TSlint注释忽略错误和RESTful理解
QT displays the specified position and size of the picture
egg中的cors和proxy(づ ̄3 ̄)づ╭~踩坑填坑的过程~ToT~
Qwebsocket communication
Processus d'exécution du programme exécutable
Several examples of pointer transfer, parameter transfer, value transfer, etc
CPT 104_ TTL 09
windows连接mysql出现ERROR 2003 (HY000): Can‘t connect to MySQL server on ‘localhost‘ (10061)
catkin_package到底干了什么
字符识别easyocr
Introduction to qqueue
[untitled] Notepad content writing area
Parameter analysis of open3d material setting
World and personal development
Why can't V-IF and V-for be used together
3d slicer中拉直体的生成
Arithmetic and logical operations
Self incrementing sequence creation of MySQL
2021-10-25