ping.go 1002 B

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