Xinqi Bao's Git

Set {r,t}xbytes 0 before incrementing them on OBSD
[slstatus.git] / components / netspeeds.c
1 /* See LICENSE file for copyright and license details. */
2 #include <stdio.h>
3 #include <limits.h>
4
5 #include "../util.h"
6
7 #if defined(__linux__)
8 #include <stdint.h>
9
10 const char *
11 netspeed_rx(const char *interface)
12 {
13 uint64_t oldrxbytes;
14 static uint64_t rxbytes = 0;
15 extern const unsigned int interval;
16 char path[PATH_MAX];
17
18 oldrxbytes = rxbytes;
19
20 snprintf(path, sizeof(path),
21 "/sys/class/net/%s/statistics/rx_bytes", interface);
22 if (pscanf(path, "%llu", &rxbytes) != 1) {
23 return NULL;
24 }
25
26 return oldrxbytes ? fmt_scaled((rxbytes - oldrxbytes) /
27 interval * 1000) : NULL;
28 }
29
30 const char *
31 netspeed_tx(const char *interface)
32 {
33 uint64_t oldtxbytes;
34 static uint64_t txbytes = 0;
35 extern const unsigned int interval;
36 char path[PATH_MAX];
37
38 oldtxbytes = txbytes;
39
40 snprintf(path, sizeof(path),
41 "/sys/class/net/%s/statistics/tx_bytes", interface);
42 if (pscanf(path, "%llu", &txbytes) != 1) {
43 return NULL;
44 }
45
46 return oldtxbytes ? fmt_scaled((txbytes - oldtxbytes) /
47 interval * 1000) : NULL;
48 }
49 #elif defined(__OpenBSD__)
50 #include <string.h>
51 #include <ifaddrs.h>
52 #include <sys/types.h>
53 #include <sys/socket.h>
54 #include <net/if.h>
55
56 const char *
57 netspeed_rx(const char *interface)
58 {
59 struct ifaddrs *ifal, *ifa;
60 struct if_data *ifd;
61 uint64_t oldrxbytes;
62 static uint64_t rxbytes = 0;
63 extern const unsigned int interval;
64 char if_ok = 0;
65
66 oldrxbytes = rxbytes;
67
68 if (getifaddrs(&ifal) == -1) {
69 warn("getifaddrs failed");
70 return NULL;
71 }
72 rxbytes = 0;
73 for (ifa = ifal; ifa; ifa = ifa->ifa_next) {
74 if (!strcmp(ifa->ifa_name, interface) &&
75 (ifd = (struct if_data *)ifa->ifa_data)) {
76 rxbytes += ifd->ifi_ibytes, if_ok = 1;
77 }
78 }
79 freeifaddrs(ifal);
80 if (!if_ok) {
81 warn("reading 'if_data' failed");
82 return NULL;
83 }
84
85 return oldrxbytes ? fmt_scaled((rxbytes - oldrxbytes) /
86 interval * 1000) : NULL;
87 }
88
89 const char *
90 netspeed_tx(const char *interface)
91 {
92 struct ifaddrs *ifal, *ifa;
93 struct if_data *ifd;
94 uint64_t oldtxbytes;
95 static uint64_t txbytes = 0;
96 extern const unsigned int interval;
97 char if_ok = 0;
98
99 oldtxbytes = txbytes;
100
101 if (getifaddrs(&ifal) == -1) {
102 warn("getifaddrs failed");
103 return NULL;
104 }
105 txbytes = 0;
106 for (ifa = ifal; ifa; ifa = ifa->ifa_next) {
107 if (!strcmp(ifa->ifa_name, interface) &&
108 (ifd = (struct if_data *)ifa->ifa_data)) {
109 txbytes += ifd->ifi_obytes, if_ok = 1;
110 }
111 }
112 freeifaddrs(ifal);
113 if (!if_ok) {
114 warn("reading 'if_data' failed");
115 return NULL;
116 }
117
118 return oldtxbytes ? fmt_scaled((txbytes - oldtxbytes) /
119 interval * 1000) : NULL;
120 }
121 #endif