Golang은 성공적으로 ping할 수 있는지 테스트합니다.

풀어 주다: 2020-01-13 15:27:37
원래의
6420명이 탐색했습니다.

Golang은 성공적으로 ping할 수 있는지 테스트합니다.

프로젝트에서는 어떤 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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!