
在项目中,我们需要知道哪些IP是可用IP,这时候想到了用ICMP(Internet控制报文协议)。可以使用开源库–github.com/sparrc/go-ping来判断是否能ping通。
使用–github.com/sparrc/go-ping开源库判断是否能ping通的代码:
func ServerPing(target string) bool {
pinger, err := ping.NewPinger(target)
if err != nil {
panic(err)
}
pinger.Count = ICMPCOUNT
pinger.Timeout = time.Duration(PINGTIME*time.Millisecond)
pinger.SetPrivileged(true)
pinger.Run()// blocks until finished
stats := pinger.Statistics()
fmt.Println(stats)
// 有回包,就是说明IP是可用的
if stats.PacketsRecv >= 1 {
return true
}
return false
}这里是通过回包数量来判断的,也可以通过掉包率来判断。同时,该库提供了Statistics结构体,包含了详细的ICMP信息,如下
type Statistics struct {
// PacketsRecv is the number of packets received.
PacketsRecv int
// PacketsSent is the number of packets sent.
PacketsSent int
// PacketLoss is the percentage of packets lost.
PacketLoss float64
// IPAddr is the address of the host being pinged.
IPAddr *net.IPAddr
// Addr is the string address of the host being pinged.
Addr string
// Rtts is all of the round-trip times sent via this pinger.
Rtts []time.Duration
// MinRtt is the minimum round-trip time sent via this pinger.
MinRtt time.Duration
// MaxRtt is the maximum round-trip time sent via this pinger.
MaxRtt time.Duration
// AvgRtt is the average round-trip time sent via this pinger.
AvgRtt time.Duration
// StdDevRtt is the standard deviation of the round-trip times sent via
// this pinger.
StdDevRtt time.Duration
}
本源码是我用过最好的淘客站源码。对于新站长很用帮助。重要!!注意上传完程序后要先登陆后台修改域名,否则会跳转到后台已设置的域名。 使用方法1:将文件夹里面的文件上传至您的空间根目录(不要在本地测试,本地测试期间功能将被限制,首页模板显示不正常!)2:访问网址http://您的网址/admin 账号:admin 密码:admin3:填写您基本网站信息,以及重要的淘客相关信息 声明:本程序使用权是本人
0
立即学习“go语言免费学习笔记(深入)”;
更多golang知识请关注PHP中文网golang教程栏目。
以上就是golang测试是否能ping通的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号