-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathNetworkInterfaceScan.h
69 lines (65 loc) · 2.17 KB
/
NetworkInterfaceScan.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
#ifdef _WIN32
#elif __APPLE__
#include <net/if.h>
#include <ifaddrs.h>
#elif __linux__
#include <net/if.h>
#include <linux/if_link.h>
#include <ifaddrs.h>
#endif
#include <string>
namespace visor::input::pcap {
static inline std::string most_used_interface()
{
#ifdef _WIN32
return std::string();
#elif __APPLE__
struct ifaddrs *ifaddr;
if (getifaddrs(&ifaddr) == -1) {
return std::string();
}
std::string interface;
uint64_t most_used = 0;
for (struct ifaddrs *ifa = ifaddr; ifa != nullptr; ifa = ifa->ifa_next) {
if (ifa->ifa_addr == nullptr || (ifa->ifa_flags & IFF_LOOPBACK) || !(ifa->ifa_flags & IFF_UP)) {
continue;
}
if (int family = ifa->ifa_addr->sa_family; family == AF_LINK && ifa->ifa_data != nullptr) {
if_data *stats = reinterpret_cast<if_data *>(ifa->ifa_data);
auto packets = stats->ifi_ipackets + stats->ifi_opackets;
if (packets > most_used) {
most_used = packets;
interface = std::string(ifa->ifa_name);
}
}
}
freeifaddrs(ifaddr);
return interface;
#elif __linux__
struct ifaddrs *ifaddr;
if (getifaddrs(&ifaddr) == -1) {
return std::string();
}
std::string interface;
uint64_t most_used = 0;
for (struct ifaddrs *ifa = ifaddr; ifa != nullptr; ifa = ifa->ifa_next) {
if (ifa->ifa_addr == nullptr || (ifa->ifa_flags & IFF_LOOPBACK) || !(ifa->ifa_flags & IFF_UP)) {
continue;
}
if (int family = ifa->ifa_addr->sa_family; family == AF_PACKET && ifa->ifa_data != nullptr) {
struct rtnl_link_stats *stats = reinterpret_cast<rtnl_link_stats *>(ifa->ifa_data);
uint64_t packets = stats->tx_packets + stats->rx_packets;
if (packets > most_used) {
most_used = packets;
interface = std::string(ifa->ifa_name);
}
}
}
freeifaddrs(ifaddr);
return interface;
#endif
}
}