An example of executing ping command under Linux OS with output parsing.
type Result struct {
AvgTime time.Duration
MaxTime time.Duration
MinTime time.Duration
MDevTime time.Duration
Transmitted int
Received int
}
func PingHostOrIp(hostOrIp string, pingCount int, timeout time.Duration) (*Result, error) {
timeoutSec := int(timeout.Seconds())
outBuff, err := exec.Command("ping", hostOrIp, "-q", fmt.Sprintf("-c %d", pingCount), fmt.Sprintf("-w %d", timeoutSec)).Output()
if err != nil {
return nil, err
}
out := string(outBuff)
reg := regexp.MustCompile(`(\d+) packets transmitted, (\d+) received, \d+% packet loss, time .+\nrtt min/avg/max/mdev = ([\d.]+)/([\d.]+)/([\d.]+)/([\d.]+) ms`)
subMatches := reg.FindStringSubmatch(out)
if subMatches == nil {
return nil, errors.New(out)
}
res := Result{
AvgTime: toDuration(subMatches[4]),
MaxTime: toDuration(subMatches[5]),
MinTime: toDuration(subMatches[3]),
MDevTime: toDuration(subMatches[6]),
Transmitted: toInt(subMatches[1]),
Received: toInt(subMatches[2]),
}
return &res, nil
}
func toInt(str string) int {
i, err := strconv.Atoi(str)
if err != nil {
panic(err)
}
return i
}
func toDuration(str string) time.Duration {
f, err := strconv.ParseFloat(str, 32)
if err != nil {
panic(err)
}
return time.Duration(100*f) * time.Microsecond
}