cd131f237544e89d50e615d2cea13b6971697db4
[sysstatus.git] / statuses / netif.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <fcntl.h>
4 #include <unistd.h>
5 #include <string.h>
6 #include "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         size_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         {
31                 statusError("status_netif",
32                         "ifpath buffer too small",
33                         ifname);
34                 return;
35         }
36         strcpy(ifpath, NETIF_BASEDIR);
37         strcat(ifpath, ifname);
38
39
40         // Is the interface up?
41         if (access(ifpath, F_OK))
42         {
43                 //printf(" ^fg(grey)[%s] ", ifname);
44                 return;
45         }
46
47
48         strcpy(&ifpath[ifpathlen], "/carrier");
49         stlen = fileRead(stline, sizeof(stline), ifpath);
50         if (stlen > 0)
51         {
52                 if (stline[0] == '1')
53                 {
54                         fputs("^fg(yellow)", stdout);
55                 }
56                 else
57                 {
58                         //fputs("^fg(red)", stdout);
59                         return;
60                 }
61         }
62
63         strcpy(&ifpath[ifpathlen], "/statistics/rx_bytes");
64         stlen = fileRead(stline, sizeof(stline), ifpath);
65         if (stlen > 0)
66                 ifsum = atof(stline);
67
68         strcpy(&ifpath[ifpathlen], "/statistics/tx_bytes");
69         stlen = fileRead(stline, sizeof(stline), ifpath);
70         if (stlen > 0)
71                 ifsum += atof(stline);
72
73
74         for(ifsumpower = 0; ifsum >= 1024.0; ifsumpower++)
75                 ifsum = ifsum / 1024;
76
77         printf(" %s: %.*f %c ", ifname,
78                                 ifsumpower ? ifsumpower - 1 : ifsumpower,
79                                 ifsum,
80                                 powerToChar(ifsumpower));
81 }