Get the round-trip time directly from the pinger
This commit is contained in:
		| @ -53,12 +53,13 @@ func CanCreateTCPConnection(address string) bool { | ||||
| 	return true | ||||
| } | ||||
|  | ||||
| // CanPing checks if an address can be pinged | ||||
| // Ping checks if an address can be pinged and returns the round-trip time if the address can be pinged | ||||
| // | ||||
| // Note that this function takes at least 100ms, even if the address is 127.0.0.1 | ||||
| func CanPing(address string) bool { | ||||
| func Ping(address string) (bool, time.Duration) { | ||||
| 	pinger, err := ping.NewPinger(address) | ||||
| 	if err != nil { | ||||
| 		return false | ||||
| 		return false, 0 | ||||
| 	} | ||||
| 	pinger.Count = 1 | ||||
| 	pinger.Timeout = 5 * time.Second | ||||
| @ -66,7 +67,10 @@ func CanPing(address string) bool { | ||||
| 	pinger.SetPrivileged(true) | ||||
| 	err = pinger.Run() | ||||
| 	if err != nil { | ||||
| 		return false | ||||
| 		return false, 0 | ||||
| 	} | ||||
| 	return true | ||||
| 	if pinger.Statistics() != nil { | ||||
| 		return true, pinger.Statistics().MaxRtt | ||||
| 	} | ||||
| 	return true, 0 | ||||
| } | ||||
|  | ||||
| @ -27,11 +27,17 @@ func TestGetHttpClient(t *testing.T) { | ||||
| 	} | ||||
| } | ||||
|  | ||||
| func TestCanPing(t *testing.T) { | ||||
| 	if !CanPing("127.0.0.1") { | ||||
| func TestPing(t *testing.T) { | ||||
| 	if success, rtt := Ping("127.0.0.1"); !success { | ||||
| 		t.Error("expected true") | ||||
| 		if rtt == 0 { | ||||
| 			t.Error("Round-trip time returned on success should've higher than 0") | ||||
| 		} | ||||
| 	} | ||||
| 	if CanPing("256.256.256.256") { | ||||
| 	if success, rtt := Ping("256.256.256.256"); success { | ||||
| 		t.Error("expected false") | ||||
| 		if rtt != 0 { | ||||
| 			t.Error("Round-trip time returned on failure should've been 0") | ||||
| 		} | ||||
| 	} | ||||
| } | ||||
|  | ||||
| @ -197,8 +197,7 @@ func (service *Service) call(result *Result) { | ||||
| 		result.Connected = client.CanCreateTCPConnection(strings.TrimPrefix(service.URL, "tcp://")) | ||||
| 		result.Duration = time.Since(startTime) | ||||
| 	} else if isServiceICMP { | ||||
| 		result.Connected = client.CanPing(strings.TrimPrefix(service.URL, "icmp://")) | ||||
| 		result.Duration = time.Since(startTime) | ||||
| 		result.Connected, result.Duration = client.Ping(strings.TrimPrefix(service.URL, "icmp://")) | ||||
| 	} else { | ||||
| 		response, err = client.GetHTTPClient(service.Insecure).Do(request) | ||||
| 		result.Duration = time.Since(startTime) | ||||
|  | ||||
		Reference in New Issue
	
	Block a user