From 363d8e1fad9d34aa5bb3b0f4dc626c4fe41c4515 Mon Sep 17 00:00:00 2001 From: Will Scott Date: Fri, 3 Mar 2023 17:22:31 +0100 Subject: [PATCH] fix #32 This chooses not to append routes that don't have source or destination when getting routes from linux It also down-weights selection of routes without gateway when all else is equal, which can be useful for choosing an underlying interface rather than a bridge interface when both are present. --- common.go | 5 +++++ netroute_linux.go | 19 +++++++++++++------ 2 files changed, 18 insertions(+), 6 deletions(-) diff --git a/common.go b/common.go index 5007397..d11c004 100644 --- a/common.go +++ b/common.go @@ -46,6 +46,11 @@ func (rt rtInfo) IsMoreSpecThan(mostSpecificRt *rtInfo) bool { return false } + // if all else is equal, prefer a route with a gateway. + if mostSpecificRt.Priority == rt.Priority && rt.Gateway == nil && mostSpecificRt.Gateway != nil { + return false + } + // Windows and MacOS hasn't metric/priority on rule entry, // But the interface device has the priority property. // diff --git a/netroute_linux.go b/netroute_linux.go index 1f039db..d94b105 100644 --- a/netroute_linux.go +++ b/netroute_linux.go @@ -60,12 +60,7 @@ loop: if err != nil { return nil, err } - switch rt.Family { - case syscall.AF_INET: - rtr.v4 = append(rtr.v4, &routeInfo) - case syscall.AF_INET6: - rtr.v6 = append(rtr.v6, &routeInfo) - default: + if rt.Family != syscall.AF_INET && rt.Family != syscall.AF_INET6 { continue loop } for _, attr := range attrs { @@ -92,6 +87,18 @@ loop: routeInfo.Priority = *(*uint32)(unsafe.Pointer(&attr.Value[0])) } } + if routeInfo.Dst == nil && routeInfo.Src == nil && routeInfo.Gateway == nil { + continue loop + } + switch rt.Family { + case syscall.AF_INET: + rtr.v4 = append(rtr.v4, &routeInfo) + case syscall.AF_INET6: + rtr.v6 = append(rtr.v6, &routeInfo) + default: + // should not happen. + continue loop + } } } sort.Sort(rtr.v4)