Xinqi Bao's Git

c846a2caf325316060da02183b7af2a19aa7e8d6
[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 const char *
9 netspeed_rx(const char *interface)
10 {
11 static int valid;
12 static unsigned long long rxbytes;
13 unsigned long oldrxbytes;
14 extern const unsigned int interval;
15 char path[PATH_MAX];
16
17 oldrxbytes = rxbytes;
18 snprintf(path, sizeof(path), "/sys/class/net/%s/statistics/rx_bytes", interface);
19 if (pscanf(path, "%llu", &rxbytes) != 1) {
20 return NULL;
21 }
22 if (!valid) {
23 valid = 1;
24 return NULL;
25 }
26
27 return fmt_scaled((rxbytes - oldrxbytes) / interval * 1000);
28 }
29
30 const char *
31 netspeed_tx(const char *interface)
32 {
33 static int valid;
34 static unsigned long long txbytes;
35 unsigned long oldtxbytes;
36 extern const unsigned int interval;
37 char path[PATH_MAX];
38
39 oldtxbytes = txbytes;
40 snprintf(path, sizeof(path), "/sys/class/net/%s/statistics/tx_bytes", interface);
41 if (pscanf(path, "%llu", &txbytes) != 1) {
42 return NULL;
43 }
44 if (!valid) {
45 valid = 1;
46 return NULL;
47 }
48
49 return fmt_scaled((txbytes - oldtxbytes) / interval * 1000);
50 }
51 #elif defined(__OpenBSD__)
52 #include <string.h>
53 #include <ifaddrs.h>
54 #include <sys/types.h>
55 #include <sys/socket.h>
56 #include <net/if.h>
57
58 const char *
59 netspeed_rx(const char *interface)
60 {
61 struct ifaddrs *ifal, *ifa;
62 struct if_data *ifd;
63 static uint64_t oldrxbytes;
64 uint64_t rxbytes = 0;
65 const char *rxs;
66 extern const unsigned int interval;
67 char if_ok = 0;
68
69 if (getifaddrs(&ifal) == -1) {
70 warn("getifaddrs failed");
71 return NULL;
72 }
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 rxs = oldrxbytes ? fmt_scaled((rxbytes - oldrxbytes) /
86 interval * 1000) : NULL;
87 return (oldrxbytes = rxbytes, rxs);
88 }
89
90 const char *
91 netspeed_tx(const char *interface)
92 {
93 struct ifaddrs *ifal, *ifa;
94 struct if_data *ifd;
95 static uint64_t oldtxbytes;
96 uint64_t txbytes = 0;
97 const char *txs;
98 extern const unsigned int interval;
99 char if_ok = 0;
100
101 if (getifaddrs(&ifal) == -1) {
102 warn("getifaddrs failed");
103 return NULL;
104 }
105 for (ifa = ifal; ifa; ifa = ifa->ifa_next) {
106 if (!strcmp(ifa->ifa_name, interface) &&
107 (ifd = (struct if_data *)ifa->ifa_data)) {
108 txbytes += ifd->ifi_obytes, if_ok = 1;
109 }
110 }
111 freeifaddrs(ifal);
112 if (!if_ok) {
113 warn("reading 'if_data' failed");
114 return NULL;
115 }
116
117 txs = oldtxbytes ? fmt_scaled((txbytes - oldtxbytes) /
118 interval * 1000) : NULL;
119 return (oldtxbytes = txbytes, txs);
120 }
121 #endif