首頁  >  文章  >  後端開發  >  golang測試是否能ping通

golang測試是否能ping通

尚
原創
2020-01-13 15:27:376436瀏覽

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知識請關注PHP中文網

golang教程欄。

以上是golang測試是否能ping通的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn