在項目中,我們需要知道哪些IP是可用IP,這時候想到了用ICMP(Internet控制報文協(xié)議)。可以使用開源庫–github.com/sparrc/go-ping來判斷是否能ping通。
為樂亭等地區(qū)用戶提供了全套網(wǎng)頁設(shè)計制作服務(wù),及樂亭網(wǎng)站建設(shè)行業(yè)解決方案。主營業(yè)務(wù)為網(wǎng)站制作、成都網(wǎng)站設(shè)計、樂亭網(wǎng)站設(shè)計,以傳統(tǒng)方式定制建設(shè)網(wǎng)站,并提供域名空間備案等一條龍服務(wù),秉承以專業(yè)、用心的態(tài)度為用戶提供真誠的服務(wù)。我們深信只要達到每一位用戶的要求,就會得到認可,從而選擇與我們長期合作。這樣,我們也可以走得更遠!
使用–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 }
這里是通過回包數(shù)量來判斷的,也可以通過掉包率來判斷。同時,該庫提供了Statistics結(jié)構(gòu)體,包含了詳細的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通的詳細內(nèi)容,更多請關(guān)注創(chuàng)新互聯(lián)其它相關(guān)文章!