Xinqi Bao's Git

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