Xinqi Bao's Git

implemented openbsd netspeed functions
[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
68 if (getifaddrs(&ifal) == -1) {
69 warn("getifaddrs failed");
70 return NULL;
71 }
72 for (ifa = ifal; ifa; ifa = ifa->ifa_next) {
73 if (!strcmp(ifa->ifa_name, interface) &&
74 (ifd = (struct if_data *)ifa->ifa_data)) {
75 rxbytes += ifd->ifi_ibytes;
76 }
77 }
78 freeifaddrs(ifal);
79
80 rxs = oldrxbytes ? fmt_scaled((rxbytes - oldrxbytes) /
81 interval * 1000) : NULL;
82 return (oldrxbytes = rxbytes, rxs);
83 }
84
85 const char *
86 netspeed_tx(const char *interface)
87 {
88 struct ifaddrs *ifal, *ifa;
89 struct if_data *ifd;
90 static uint64_t oldtxbytes;
91 uint64_t txbytes = 0;
92 const char *txs;
93 extern const unsigned int interval;
94
95 if (getifaddrs(&ifal) == -1) {
96 warn("getifaddrs failed");
97 return NULL;
98 }
99 for (ifa = ifal; ifa; ifa = ifa->ifa_next) {
100 if (!strcmp(ifa->ifa_name, interface) &&
101 (ifd = (struct if_data *)ifa->ifa_data)) {
102 txbytes += ifd->ifi_obytes;
103 }
104 }
105 freeifaddrs(ifal);
106
107 txs = oldtxbytes ? fmt_scaled((txbytes - oldtxbytes) /
108 interval * 1000) : NULL;
109 return (oldtxbytes = txbytes, txs);
110 }
111 #endif