diff --git a/lib/netutil/netutil.go b/lib/netutil/netutil.go index d1b4a7f5b..ee042a5b3 100644 --- a/lib/netutil/netutil.go +++ b/lib/netutil/netutil.go @@ -6,7 +6,14 @@ package netutil -import "net/url" +import ( + "fmt" + "net" + "net/url" + "os" + + "github.com/jackpal/gateway" +) // Address constructs a URL from the given network and hostname. func AddressURL(network, host string) string { @@ -16,3 +23,22 @@ func AddressURL(network, host string) string { } return u.String() } + +// Gateway returns the IP address of the default network gateway. +func Gateway() (ip net.IP, err error) { + ip, err = gateway.DiscoverGateway() + if err != nil { + // Fails on Android 14+ due to permission denied error when reading + // /proc/net/route. The wrapper may give a hint then because it is + // able to discover the gateway from java code. + if v := os.Getenv("FALLBACK_NET_GATEWAY_IPV4"); v != "" { + ip = net.ParseIP(v) + if ip == nil { + return nil, fmt.Errorf("%q: invalid IP", v) + } + return ip, nil + } + return ip, err + } + return ip, nil +} diff --git a/lib/pmp/pmp.go b/lib/pmp/pmp.go index d6b71f669..e5acf1409 100644 --- a/lib/pmp/pmp.go +++ b/lib/pmp/pmp.go @@ -14,10 +14,10 @@ import ( "strings" "time" - "github.com/jackpal/gateway" natpmp "github.com/jackpal/go-nat-pmp" "github.com/syncthing/syncthing/lib/nat" + "github.com/syncthing/syncthing/lib/netutil" "github.com/syncthing/syncthing/lib/osutil" "github.com/syncthing/syncthing/lib/svcutil" ) @@ -30,7 +30,7 @@ func Discover(ctx context.Context, renewal, timeout time.Duration) []nat.Device var ip net.IP err := svcutil.CallWithContext(ctx, func() error { var err error - ip, err = gateway.DiscoverGateway() + ip, err = netutil.Gateway() return err }) if err != nil {