ohmu
·
2026-10-15
1#include "netio.h"
2
3#include "common/debug.h"
4#include "common/io.h"
5#include "common/netif.h"
6#include "common/strutil.h"
7
8#include <fcntl.h>
9#include <net/if.h>
10
11static void getData(FFstrbuf* buffer, const char* ifName, bool isDefaultRoute, int basefd, FFlist* result) {
12 FF_AUTO_CLOSE_FD int dfd = openat(basefd, ifName, O_RDONLY | O_DIRECTORY);
13 if (dfd < 0) {
14 return;
15 }
16
17 char operstate;
18 if (!ffReadFileDataRelative(dfd, "operstate", 1, &operstate) || operstate != 'u' /* up or unknown */) {
19 return;
20 }
21
22 FFNetIOResult* counters = FF_LIST_ADD(FFNetIOResult, *result);
23 ffStrbufInitS(&counters->name, ifName);
24 counters->defaultRoute = isDefaultRoute;
25
26 if (ffReadFileBufferRelative(dfd, "statistics/rx_bytes", buffer)) {
27 counters->rxBytes = ffStrbufToUInt(buffer, 0);
28 }
29
30 if (ffReadFileBufferRelative(dfd, "statistics/tx_bytes", buffer)) {
31 counters->txBytes = ffStrbufToUInt(buffer, 0);
32 }
33
34 if (ffReadFileBufferRelative(dfd, "statistics/rx_packets", buffer)) {
35 counters->rxPackets = ffStrbufToUInt(buffer, 0);
36 }
37
38 if (ffReadFileBufferRelative(dfd, "statistics/tx_packets", buffer)) {
39 counters->txPackets = ffStrbufToUInt(buffer, 0);
40 }
41
42 if (ffReadFileBufferRelative(dfd, "statistics/rx_errors", buffer)) {
43 counters->rxErrors = ffStrbufToUInt(buffer, 0);
44 }
45
46 if (ffReadFileBufferRelative(dfd, "statistics/tx_errors", buffer)) {
47 counters->txErrors = ffStrbufToUInt(buffer, 0);
48 }
49
50 if (ffReadFileBufferRelative(dfd, "statistics/rx_dropped", buffer)) {
51 counters->rxDrops = ffStrbufToUInt(buffer, 0);
52 }
53
54 if (ffReadFileBufferRelative(dfd, "statistics/tx_dropped", buffer)) {
55 counters->txDrops = ffStrbufToUInt(buffer, 0);
56 }
57}
58
59const char* ffNetIOGetIoCounters(FFlist* result, FFNetIOOptions* options) {
60 FF_AUTO_CLOSE_DIR DIR* dirp = opendir("/sys/class/net");
61 if (!dirp) {
62 FF_DEBUG("opendir(\"/sys/class/net\") failed: %s", strerror(errno));
63 return "opendir(\"/sys/class/net\") == nullptr";
64 }
65
66 FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate();
67
68 const char* defaultRouteIfName = ffNetifGetDefaultRouteV4()->ifName;
69
70 if (options->defaultRouteOnly) {
71 if (options->namePrefix.length && strncmp(defaultRouteIfName, options->namePrefix.chars, options->namePrefix.length) != 0) {
72 return nullptr;
73 }
74
75 getData(&buffer, defaultRouteIfName, true, dirfd(dirp), result);
76 } else {
77 struct dirent* entry;
78 while ((entry = readdir(dirp)) != nullptr) {
79 const char* ifName = entry->d_name;
80 if (ifName[0] == '.') {
81 continue;
82 }
83
84 if (options->namePrefix.length && strncmp(ifName, options->namePrefix.chars, options->namePrefix.length) != 0) {
85 continue;
86 }
87
88 getData(&buffer, ifName, ffStrEquals(ifName, defaultRouteIfName), dirfd(dirp), result);
89 }
90 }
91
92 return nullptr;
93}