ping.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  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. "context"
  9. "net/url"
  10. "time"
  11. "github.com/syncthing/syncthing/lib/dialer"
  12. )
  13. // TCPPing returns the duration required to establish a TCP connection
  14. // to the given host. ICMP packets require root privileges, hence why we use
  15. // tcp.
  16. func TCPPing(ctx context.Context, address string) (time.Duration, error) {
  17. start := time.Now()
  18. ctx, cancel := context.WithTimeout(ctx, time.Second)
  19. defer cancel()
  20. conn, err := dialer.DialContext(ctx, "tcp", address)
  21. if err == 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(ctx context.Context, addr string) (time.Duration, error) {
  29. uri, err := url.Parse(addr)
  30. if err != nil {
  31. return 0, err
  32. }
  33. return TCPPing(ctx, uri.Host)
  34. }