forked from syncthing/syncthing
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ping.go
37 lines (31 loc) · 1002 Bytes
/
ping.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// Copyright (C) 2015 The Syncthing Authors.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at https://mozilla.org/MPL/2.0/.
package osutil
import (
"net/url"
"time"
"github.com/syncthing/syncthing/lib/dialer"
)
// TCPPing returns the duration required to establish a TCP connection
// to the given host. ICMP packets require root privileges, hence why we use
// tcp.
func TCPPing(address string) (time.Duration, error) {
start := time.Now()
conn, err := dialer.DialTimeout("tcp", address, time.Second)
if conn != nil {
conn.Close()
}
return time.Since(start), err
}
// GetLatencyForURL parses the given URL, tries opening a TCP connection to it
// and returns the time it took to establish the connection.
func GetLatencyForURL(addr string) (time.Duration, error) {
uri, err := url.Parse(addr)
if err != nil {
return 0, err
}
return TCPPing(uri.Host)
}