Ye Olde Brick, hacked one very late night in 2010.
[sysstatus.git] / statuses / netif_named.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <fcntl.h>
4 #include <unistd.h>
5 #include <string.h>
6 #include "netif_named.h"
7 #include "tools.h"
8
9 #define NETIF_BASEDIR "/sys/class/net/"
10
11 void status_netif_named(char *ifname)
12 {
13         char stline[16];
14         int stfile;
15         size_t stlen;
16         
17         double ifsum;
18         int ifsumpower;
19         
20         char *stfilename = NULL;
21         
22         stfilename = malloc(sizeof(NETIF_BASEDIR) - 1 + strlen(ifname) + sizeof("/statistics/rx_bytes"));
23         
24         strcpy(stfilename, NETIF_BASEDIR);
25         strcat(stfilename, ifname);
26         
27         if (access(stfilename, F_OK))
28         {
29                 //printf(" ^fg(grey)[%s] ", ifname);
30                 return;
31         }
32         
33         strcat(stfilename, "/carrier");
34         stfile = open(stfilename, 0);
35         if (stfile != -1)
36         {
37                 stlen = read(stfile, stline, sizeof(stline) - 1);
38                 close(stfile);
39                 if (stline[0] == '1')
40                         fputs("^fg(yellow)", stdout);
41                 else
42                 {
43                         //fputs("^fg(red)", stdout);
44                         return;
45                 }
46         }
47         
48         strcpy(stfilename, NETIF_BASEDIR);
49         strcat(stfilename, ifname);
50         strcat(stfilename, "/statistics/rx_bytes");
51         stfile = open(stfilename, 0);
52         if (stfile != -1)
53         {
54                 stlen = read(stfile, stline, sizeof(stline) - 1);
55                 close(stfile);
56                 stline[stlen] = '\0';
57                 ifsum = atof(stline);
58         }
59
60         strcpy(stfilename, NETIF_BASEDIR);
61         strcat(stfilename, ifname);
62         strcat(stfilename, "/statistics/tx_bytes");
63         stfile = open(stfilename, 0);
64         if (stfile != -1)
65         {
66                 stlen = read(stfile, stline, sizeof(stline) - 1);
67                 close(stfile);
68                 stline[stlen] = '\0';
69                 ifsum += atof(stline);
70         }
71         
72         for(ifsumpower = 0; ifsum >= 1024.0; ifsumpower++)
73                 ifsum = ifsum / 1024;
74         
75         printf(" %s: %.*f %c ", ifname, ifsumpower ? ifsumpower - 1 : ifsumpower, ifsum, powertochar(ifsumpower));
76 }