2015-06-23 12:55:30 +00:00
|
|
|
// 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 http://mozilla.org/MPL/2.0/.
|
|
|
|
|
|
|
|
package osutil
|
|
|
|
|
|
|
|
import (
|
2015-09-02 16:56:44 +00:00
|
|
|
"net/url"
|
2015-06-23 12:55:30 +00:00
|
|
|
"time"
|
2016-01-30 01:52:32 +00:00
|
|
|
|
|
|
|
"github.com/syncthing/syncthing/lib/dialer"
|
2015-06-23 12:55:30 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// TCPPing returns the duration required to establish a TCP connection
|
2016-05-08 10:54:22 +00:00
|
|
|
// to the given host. ICMP packets require root privileges, hence why we use
|
2015-06-23 12:55:30 +00:00
|
|
|
// tcp.
|
|
|
|
func TCPPing(address string) (time.Duration, error) {
|
|
|
|
start := time.Now()
|
2016-01-30 01:52:32 +00:00
|
|
|
conn, err := dialer.DialTimeout("tcp", address, time.Second)
|
2015-06-23 12:55:30 +00:00
|
|
|
if conn != nil {
|
|
|
|
conn.Close()
|
|
|
|
}
|
|
|
|
return time.Since(start), err
|
|
|
|
}
|
2015-09-02 16:56:44 +00:00
|
|
|
|
|
|
|
// 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)
|
|
|
|
}
|