ping.go 1010 B

123456789101112131415161718192021222324252627282930313233343536373839
  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 http://mozilla.org/MPL/2.0/.
  6. package osutil
  7. import (
  8. "net"
  9. "net/url"
  10. "time"
  11. )
  12. // TCPPing returns the duration required to establish a TCP connection
  13. // to the given host. ICMP packets require root priviledges, hence why we use
  14. // tcp.
  15. func TCPPing(address string) (time.Duration, error) {
  16. dialer := net.Dialer{
  17. Deadline: time.Now().Add(time.Second),
  18. }
  19. start := time.Now()
  20. conn, err := dialer.Dial("tcp", address)
  21. if conn != nil {
  22. conn.Close()
  23. }
  24. return time.Since(start), err
  25. }
  26. // GetLatencyForURL parses the given URL, tries opening a TCP connection to it
  27. // and returns the time it took to establish the connection.
  28. func GetLatencyForURL(addr string) (time.Duration, error) {
  29. uri, err := url.Parse(addr)
  30. if err != nil {
  31. return 0, err
  32. }
  33. return TCPPing(uri.Host)
  34. }