How to get the active WAN interface from Ubus in Lua?

Is there a preferred way for a Lua script to get the Ubus interface name (i.e. network.interface.????) of the interface that's currently providing the default route?

Ultimately, I'm looking for a way to reliably get the WAN-side IP address regardless of which interface it is attached to.

I know how to get the IP addresses of an interface from Ubus, but I can't figure out how to get routing information from Ubus to know which interface is currently providing WAN connectivity. If OpenWRT is terminating a PPPoE or VPN connection, the actual WAN interface will be the PPPoE/VPN interface and not the one named 'wan.'

Isn't the best way to lookup the route with the ip tool? Include one or more optional parameters if you use policy based routing.

ip route get [ ROUTE_GET_FLAGS ] ADDRESS
                            [ from ADDRESS iif STRING ]
                            [ oif STRING ] [ tos TOS ]
                            [ mark NUMBER ] [ vrf NAME ]
                            [ uid NUMBER ] [ ipproto PROTOCOL ]
                            [ sport NUMBER ] [ dport NUMBER ]

I was hoping for an easier way to do this.

Getting the output into ip route get into a usable form in Lua would seem to require a lot of glue logic. OpenWRT's Lua interpreter does not include io.popen, so simply getting the output of a shell command into a Lua script is awkward. Ip route get also returns a device name, which cannot be readily mapped to the ubus interface namespace which exposes addressing information.

These problems are solvable, but at the cost of maybe 100-200 lines of code, which is a level of effort I'd rather not undertake if there is an easier way.


local sys  = require "luci.sys"
local defroute
defroute = luci.sys.exec("ip route | grep '^default' 2>/dev/null")
if defroute then