這篇文章將為大家詳細(xì)講解有關(guān)golang中怎么測(cè)試是否能ping通,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個(gè)參考,希望大家閱讀完這篇文章后對(duì)相關(guān)知識(shí)有一定的了解。
創(chuàng)新互聯(lián)專注于金安網(wǎng)站建設(shè)服務(wù)及定制,我們擁有豐富的企業(yè)做網(wǎng)站經(jīng)驗(yàn)。 熱誠(chéng)為您提供金安營(yíng)銷型網(wǎng)站建設(shè),金安網(wǎng)站制作、金安網(wǎng)頁(yè)設(shè)計(jì)、金安網(wǎng)站官網(wǎng)定制、微信小程序開發(fā)服務(wù),打造金安網(wǎng)絡(luò)公司原創(chuàng)品牌,更為您提供金安網(wǎng)站排名全網(wǎng)營(yíng)銷落地服務(wù)。在項(xiàng)目中,我們需要知道哪些IP是可用IP,這時(shí)候想到了用ICMP(Internet控制報(bào)文協(xié)議)??梢允褂瞄_源庫(kù)–github.com/sparrc/go-ping來判斷是否能ping通。
使用–github.com/sparrc/go-ping開源庫(kù)判斷是否能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ù)量來判斷的,也可以通過掉包率來判斷。同時(shí),該庫(kù)提供了Statistics結(jié)構(gòu)體,包含了詳細(xì)的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 }
關(guān)于golang中怎么測(cè)試是否能ping通就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。
文章名稱:golang中怎么測(cè)試是否能ping通-創(chuàng)新互聯(lián)
URL鏈接:http://www.rwnh.cn/article40/dsohho.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供服務(wù)器托管、網(wǎng)站設(shè)計(jì)公司、搜索引擎優(yōu)化、標(biāo)簽優(yōu)化、定制網(wǎng)站、面包屑導(dǎo)航
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容