In the project, we need to know which IPs are available IPs, so we thought of using ICMP (Internet Control Message Protocol). You can use the open source library –github.com/sparrc/go-ping to determine whether the ping can succeed.
Use the –github.com/sparrc/go-ping open source library to determine whether the ping can be successful:
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 }
This is judged by the number of returned packets, or by the packet drop rate. judge. At the same time, the library provides the Statistics structure, including detailed ICMP information, as follows
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 }
For more golang knowledge, please pay attention to the PHP Chinese websitegolang tutorialcolumn.
The above is the detailed content of Golang tests whether it can ping successfully. For more information, please follow other related articles on the PHP Chinese website!