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.
This commit is contained in:
H. James Zhao 2022-01-18 13:53:19 -05:00 committed by GitHub
parent d995a39da8
commit 8a9cad2792
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 11 additions and 0 deletions

View File

@ -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;
}