Better file structure and build system
[sysstatus.git] / src / status / netif.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <unistd.h>
4 #include <string.h>
5
6 #include "status/netif.h"
7 #include "tools.h"
8 #include "config.h"
9
10 #ifndef NETIF_BASEDIR
11   #define NETIF_BASEDIR "/sys/class/net/"
12 #endif
13
14
15 void status_netif(char *ifname)
16 {
17   char ifpath[256];
18   int ifpathlen;
19
20   char stline[16];
21   ssize_t stlen;
22
23   double ifsum = 0.0;
24   int ifsumpower;
25
26
27   /* Prepare path */
28   ifpathlen = sizeof(NETIF_BASEDIR) - 1 + strlen(ifname);
29   if (ifpathlen + 1 + sizeof("/statistics/rx_bytes") >= sizeof(ifpath)) {
30     statusError("status_netif",
31                 "ifpath buffer too small",
32                 ifname);
33     return;
34   }
35   strcpy(ifpath, NETIF_BASEDIR);
36   strcat(ifpath, ifname);
37
38
39   /* Is the interface up? */
40   if (access(ifpath, F_OK)) {
41     //printf(" ^fg(grey)[%s] ", ifname);
42     return;
43   }
44
45
46   strcpy(&ifpath[ifpathlen], "/carrier");
47   stlen = fileRead(stline, sizeof(stline), ifpath);
48   if (stlen > 0) {
49     if (stline[0] == '1') {
50       fputs("^fg(yellow)", stdout);
51     } else {
52       //fputs("^fg(red)", stdout);
53       return;
54     }
55   } else {
56     return;
57   }
58
59   strcpy(&ifpath[ifpathlen], "/statistics/rx_bytes");
60   stlen = fileRead(stline, sizeof(stline), ifpath);
61   if (stlen > 0) {
62     ifsum = atof(stline);
63   }
64
65   strcpy(&ifpath[ifpathlen], "/statistics/tx_bytes");
66   stlen = fileRead(stline, sizeof(stline), ifpath);
67   if (stlen > 0) {
68     ifsum += atof(stline);
69   }
70
71
72   for(ifsumpower = 0; ifsum >= 1024.0; ifsumpower++) {
73     ifsum = ifsum / 1024;
74   }
75
76   printf(" %s: %.*f %c ", ifname,
77                           ifsumpower ? ifsumpower - 1 : ifsumpower,
78                           ifsum,
79                           powerToChar(ifsumpower));
80 }