Golang tests whether it can ping successfully

Release: 2020-01-13 15:27:37
Original
6370 people have browsed it

Golang tests whether it can ping successfully

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 }
Copy after login

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 }
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!