golang中怎么测试是否能ping通-创新互联

这篇文章将为大家详细讲解有关golang中怎么测试是否能ping通,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

创新互联专注于金安网站建设服务及定制,我们拥有丰富的企业做网站经验。 热诚为您提供金安营销型网站建设,金安网站制作、金安网页设计、金安网站官网定制、微信小程序开发服务,打造金安网络公司原创品牌,更为您提供金安网站排名全网营销落地服务。

在项目中,我们需要知道哪些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通就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

文章名称:golang中怎么测试是否能ping通-创新互联
URL链接:https://www.cdcxhl.com/article40/dsohho.html

成都网站建设公司_创新互联,为您提供服务器托管网站设计公司搜索引擎优化标签优化定制网站面包屑导航

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

成都网页设计公司