Xinqi Bao's Git

Add network speed 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 /* unimplemented */
53 #endif