使用–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知识请关注golang教程栏目。
以上就是golang测试是否能ping通的详细内容。