在项目中,我们需要知道哪些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通的详细内容,更多请关注创新互联其它相关文章!