netutil.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. // Copyright (C) 2023 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 netutil
  7. import (
  8. "fmt"
  9. "net"
  10. "net/url"
  11. "os"
  12. "github.com/jackpal/gateway"
  13. )
  14. // Address constructs a URL from the given network and hostname.
  15. func AddressURL(network, host string) string {
  16. u := url.URL{
  17. Scheme: network,
  18. Host: host,
  19. }
  20. return u.String()
  21. }
  22. // Gateway returns the IP address of the default network gateway.
  23. func Gateway() (ip net.IP, err error) {
  24. ip, err = gateway.DiscoverGateway()
  25. if err != nil {
  26. // Fails on Android 14+ due to permission denied error when reading
  27. // /proc/net/route. The wrapper may give a hint then because it is
  28. // able to discover the gateway from java code.
  29. if v := os.Getenv("FALLBACK_NET_GATEWAY_IPV4"); v != "" {
  30. ip = net.ParseIP(v)
  31. if ip == nil {
  32. return nil, fmt.Errorf("%q: invalid IP", v)
  33. }
  34. return ip, nil
  35. }
  36. return ip, err
  37. }
  38. return ip, nil
  39. }