github.com/keysonZZZ/kmg@v0.0.0-20151121023212-05317bfd7d39/kmgNet/kmgPing/kmgPing.go (about)

     1  package kmgPing
     2  
     3  import (
     4  	"github.com/tatsushid/go-fastping"
     5  	"net"
     6  	"time"
     7  	"github.com/bronze1man/kmg/kmgLog"
     8  )
     9  
    10  type EchoStatus string
    11  
    12  const (
    13  	EchoStatusSuccess EchoStatus = "Success"
    14  	EchoStatusFail    EchoStatus = "Fail"
    15  )
    16  
    17  type Echo struct {
    18  	Rtt     time.Duration
    19  	Status  EchoStatus
    20  	Address string
    21  }
    22  
    23  // 丢包返回1,不丢包返回0
    24  func (e Echo) GetLostRateFloat()float64{
    25  	if e.Status==EchoStatusSuccess{
    26  		return 0
    27  	}else{
    28  		return 1
    29  	}
    30  }
    31  
    32  var MaxRtt time.Duration = time.Duration(1e9)
    33  
    34  func Ping(address string) Echo {
    35  	p := fastping.NewPinger()
    36  	p.MaxRTT = MaxRtt
    37  	ra, err := net.ResolveIPAddr("ip4:icmp", address)
    38  	handleErr(err)
    39  	p.AddIPAddr(ra)
    40  	echo := Echo{
    41  		Address: address,
    42  	}
    43  	p.OnRecv = func(addr *net.IPAddr, rtt time.Duration) {
    44  		echo.Rtt = rtt
    45  		echo.Status = EchoStatusSuccess
    46  	}
    47  	p.OnIdle = func() {
    48  		if echo.Status == EchoStatusSuccess {
    49  			return
    50  		}
    51  		echo.Status = EchoStatusFail
    52  		echo.Rtt = time.Duration(1e9)
    53  	}
    54  	err = p.Run()
    55  	handleErr(err)
    56  	if echo.Rtt==0 && echo.Status==EchoStatusSuccess{
    57  		kmgLog.Log("error","[kmgPing.Ping] echo.Rtt==0 && echo.Status==EchoStatusSuccess",address)
    58  	}
    59  	return echo
    60  }
    61  
    62  func handleErr(err error) {
    63  	if err != nil {
    64  		panic(err)
    65  	}
    66  }