golang测试是否能ping通

互联网 20-1-13

在项目中,我们需要知道哪些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 }
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 }

更多golang知识请关注PHP中文网golang教程栏目。

以上就是golang测试是否能ping通的详细内容,更多内容请关注技术你好其它相关文章!

来源链接:
免责声明:
1.资讯内容不构成投资建议,投资者应独立决策并自行承担风险
2.本文版权归属原作所有,仅代表作者本人观点,不代表本站的观点或立场
标签: golang
上一篇:php获取远程图片并下载保存到本地的方法分析 下一篇:golang怎样读取json数据

相关资讯