From 8a9cad27929ac7cf1ef10ffb9e8dc14f9391e2f8 Mon Sep 17 00:00:00 2001 From: "H. James Zhao" Date: Tue, 18 Jan 2022 13:53:19 -0500 Subject: [PATCH] net: prefer running interface for auto-detection (#2557) Improve the find_interface() to return a interface name that is currently running if any interface of given type is currently running, else just return the first one found. This will allow the interface-type to work with multiple net interface of the same type, and prefer to one that is currently connect to a network. This works great HW with multiple ethernet port and user expect to occasonally swap between the two. --- src/adapters/net.cpp | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/adapters/net.cpp b/src/adapters/net.cpp index 1fc5f182..b8334924 100644 --- a/src/adapters/net.cpp +++ b/src/adapters/net.cpp @@ -98,12 +98,23 @@ namespace net { std::string find_interface(NetType type) { struct ifaddrs* ifaddrs; getifaddrs(&ifaddrs); + + struct ifaddrs* candidate_if = nullptr; + for (struct ifaddrs* i = ifaddrs; i != nullptr; i = i->ifa_next) { const std::string name{i->ifa_name}; const NetType iftype = iface_type(name); if (iftype != type) { continue; } + if (candidate_if == nullptr) { + candidate_if = i; + } else if (((candidate_if->ifa_flags & IFF_RUNNING) == 0) && ((i->ifa_flags & IFF_RUNNING) > 0)) { + candidate_if = i; + } + } + if (candidate_if) { + const std::string name{candidate_if->ifa_name}; freeifaddrs(ifaddrs); return name; }