
프로젝트에서는 어떤 IP가 사용 가능한 IP인지 알아야 하므로 ICMP(Internet Control Message Protocol)를 사용하기로 했습니다. 오픈 소스 라이브러리 –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
}이는 반환된 패킷 수 또는 패킷 삭제 비율로 판단됩니다. 동시에 라이브러리는 다음과 같이 자세한 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 지식을 보려면 PHP 중국어 웹사이트 golang tutorial 칼럼을 주목하세요.
위 내용은 Golang은 성공적으로 ping할 수 있는지 테스트합니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!