NetworkMgr: Use cheaper/simpler hasDefaultRoute in isOnline

Device:getDefaultRoute parses /proc/net/route and converts the hex
addresses to textual IP addresses, but in `isOnline` we don't care what
address the gateway actually has, we only care about whether we have a
default route into the Internet.

This provides a simpler alternative that does the equivalent of
"ip route get 1.1.1.1" and returns true if we have a route. It's also
much easier to extend this for IPv6-only networks, although that isn't
implemented yet (PocketBook has no IPv6 support).
reviewable/pr11601/r1
Tomas Janousek 2 months ago
parent 9b94ebb548
commit 30a490bb11

@ -274,6 +274,30 @@ function NetworkMgr:ifHasAnAddress()
return ok
end
-- The socket API equivalent of "ip route get 1.1.1.1".
function NetworkMgr:hasDefaultRoute()
local socket = require("socket")
local s, ret, err
s, err = socket.udp()
if s == nil then
logger.err("NetworkMgr: socket.udp:", err)
return nil
end
--- @todo: Try 2606:4700:4700::1111 if IPv4 is unavailable.
ret, err = s:setpeername("1.1.1.1", "53")
if ret == nil then
-- Most likely "Network is unreachable", meaning there's no route to that address.
logger.dbg("NetworkMgr: socket.udp.setpeername:", err)
end
s:close()
-- If setpeername succeeded, we have a default route.
return ret ~= nil
end
-- Wrappers around turnOnWifi & turnOffWifi with proper Event signaling
function NetworkMgr:enableWifi(wifi_cb, connectivity_cb, connectivity_widget, interactive)
local status = self:requestToTurnOnWifi(wifi_cb, interactive)
@ -534,7 +558,7 @@ function NetworkMgr:isOnline()
-- Fail early if we don't even have a default route.
-- On PocketBook devices, if the first call to socket.dns.toip(…) fails, it never succeeds again.
if not Device:getDefaultRoute() then
if not self:hasDefaultRoute() then
return false
end

Loading…
Cancel
Save