net/interfaces: better handle multiple interfaces in LikelyHomeRouterIP

Currently, we get the "likely home router" gateway IP and then iterate
through all IPs for all interfaces trying to match IPs to determine the
source IP. However, on many platforms we know what interface the gateway
is through, and thus we don't need to iterate through all interfaces
checking IPs. Instead, use the IP address of the associated interface.

This better handles the case where we have multiple interfaces on a
system all connected to the same gateway, and where the first interface
that we visit (as iterated by ForeachInterfaceAddress) isn't also the
default internet route.

Updates #8992

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I8632f577f1136930f4ec60c76376527a19a47d1f
This commit is contained in:
Andrew Dunham
2023-12-19 16:27:52 -05:00
parent 7a2eb22e94
commit 01286af82b
6 changed files with 83 additions and 25 deletions

View File

@ -86,16 +86,16 @@ func init() {
likelyHomeRouterIP = likelyHomeRouterIPBSDFetchRIB
}
func likelyHomeRouterIPBSDFetchRIB() (ret netip.Addr, ok bool) {
func likelyHomeRouterIPBSDFetchRIB() (ret, myIP netip.Addr, ok bool) {
rib, err := fetchRoutingTable()
if err != nil {
log.Printf("routerIP/FetchRIB: %v", err)
return ret, false
return ret, myIP, false
}
msgs, err := parseRoutingTable(rib)
if err != nil {
log.Printf("routerIP/ParseRIB: %v", err)
return ret, false
return ret, myIP, false
}
for _, m := range msgs {
rm, ok := m.(*route.RouteMessage)
@ -110,10 +110,18 @@ func likelyHomeRouterIPBSDFetchRIB() (ret netip.Addr, ok bool) {
if !ok {
continue
}
return netaddr.IPv4(gw.IP[0], gw.IP[1], gw.IP[2], gw.IP[3]), true
// If the route entry has an interface address associated with
// it, then parse and return that. This is optional.
if len(rm.Addrs) >= unix.RTAX_IFA {
if addr, ok := rm.Addrs[unix.RTAX_IFA].(*route.Inet4Addr); ok {
myIP = netaddr.IPv4(addr.IP[0], addr.IP[1], addr.IP[2], addr.IP[3])
}
}
return netaddr.IPv4(gw.IP[0], gw.IP[1], gw.IP[2], gw.IP[3]), myIP, true
}
return ret, false
return ret, myIP, false
}
var v4default = [4]byte{0, 0, 0, 0}