温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

使用go语言测试能ping通吗?

发布时间:2020-05-22 17:09:36 来源:亿速云 阅读:687 作者:鸽子 栏目:编程语言

在项目中,我们需要知道哪些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测试是否能ping通的详细内容,更多请关注亿速云其它相关文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI