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

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

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

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。

  • 相关标签:golang
  • 程序员必备接口测试调试工具:点击使用

    Apipost = Postman + Swagger + Mock + Jmeter

    Api设计、调试、文档、自动化测试工具

    网页生成APP,用做网站的技术去做APP:立即创建

    手机网站开发APP、自助封装APP、200+原生模块、2000+映射JS接口按需打包

    • 上一篇:golang怎样读取json数据
    • 下一篇:go语言结构体组合函数介绍

    相关文章

    相关视频


    • golang怎么判断map是否为空
    • Golang怎么判断int是否为空
    • Golang怎么判断是否为ip
    • golang怎么判断指针是否为空
    • golang测试是否能ping通
    • SSDB GO语言api文档
    • go语言介绍和环境搭建1
    • go语言介绍和环境搭建2

    视频教程分类

    • php视频教程
    • html视频教程
    • css视频教程
    • JS视频教程
    • jQuery视频教程
    • mysql视频教程
    • Linux视频教程
    • Python视频教程
    • Laravel视频教程
    • Vue视频教程

    专题

    golang测试是否能ping通