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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
|
#include "netio.h"
#include "common/io.h"
#include "common/netif.h"
#include "common/strutil.h"
#include <fcntl.h>
#include <net/if.h>
static void getData(FFstrbuf* buffer, const char* ifName, bool isDefaultRoute, int basefd, FFlist* result) {
FF_AUTO_CLOSE_FD int dfd = openat(basefd, ifName, O_RDONLY | O_DIRECTORY);
if (dfd < 0) {
return;
}
char operstate;
if (!ffReadFileDataRelative(dfd, "operstate", 1, &operstate) || operstate != 'u' /* up or unknown */) {
return;
}
FFNetIOResult* counters = FF_LIST_ADD(FFNetIOResult, *result);
ffStrbufInitS(&counters->name, ifName);
counters->defaultRoute = isDefaultRoute;
if (ffReadFileBufferRelative(dfd, "statistics/rx_bytes", buffer)) {
counters->rxBytes = ffStrbufToUInt(buffer, 0);
}
if (ffReadFileBufferRelative(dfd, "statistics/tx_bytes", buffer)) {
counters->txBytes = ffStrbufToUInt(buffer, 0);
}
if (ffReadFileBufferRelative(dfd, "statistics/rx_packets", buffer)) {
counters->rxPackets = ffStrbufToUInt(buffer, 0);
}
if (ffReadFileBufferRelative(dfd, "statistics/tx_packets", buffer)) {
counters->txPackets = ffStrbufToUInt(buffer, 0);
}
if (ffReadFileBufferRelative(dfd, "statistics/rx_errors", buffer)) {
counters->rxErrors = ffStrbufToUInt(buffer, 0);
}
if (ffReadFileBufferRelative(dfd, "statistics/tx_errors", buffer)) {
counters->txErrors = ffStrbufToUInt(buffer, 0);
}
if (ffReadFileBufferRelative(dfd, "statistics/rx_dropped", buffer)) {
counters->rxDrops = ffStrbufToUInt(buffer, 0);
}
if (ffReadFileBufferRelative(dfd, "statistics/tx_dropped", buffer)) {
counters->txDrops = ffStrbufToUInt(buffer, 0);
}
}
const char* ffNetIOGetIoCounters(FFlist* result, FFNetIOOptions* options) {
FF_AUTO_CLOSE_DIR DIR* dirp = opendir("/sys/class/net");
if (!dirp) {
return "opendir(\"/sys/class/net\") == NULL";
}
FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate();
const char* defaultRouteIfName = ffNetifGetDefaultRouteV4()->ifName;
if (options->defaultRouteOnly) {
if (options->namePrefix.length && strncmp(defaultRouteIfName, options->namePrefix.chars, options->namePrefix.length) != 0) {
return NULL;
}
getData(&buffer, defaultRouteIfName, true, dirfd(dirp), result);
} else {
struct dirent* entry;
while ((entry = readdir(dirp)) != NULL) {
const char* ifName = entry->d_name;
if (ifName[0] == '.') {
continue;
}
if (options->namePrefix.length && strncmp(ifName, options->namePrefix.chars, options->namePrefix.length) != 0) {
continue;
}
getData(&buffer, ifName, ffStrEquals(ifName, defaultRouteIfName), dirfd(dirp), result);
}
}
return NULL;
}
|