network.c (1083B)
1 #include <stdio.h> 2 3 #ifdef UP_SPEED 4 #define PREV_FILE_LOC "/tmp/network_up_previous" 5 #define BYTES_FILE_LOC "/sys/class/net/wlp0s20f3/statistics/tx_bytes" 6 #else 7 #define PREV_FILE_LOC "/tmp/network_down_previous" 8 #define BYTES_FILE_LOC "/sys/class/net/wlp0s20f3/statistics/rx_bytes" 9 #endif 10 11 int get_previous_value() { 12 FILE *f; 13 f = fopen(PREV_FILE_LOC, "r"); 14 if (f == NULL) { 15 return 0; 16 } 17 char buf[100]; 18 fgets(buf, 100, f); 19 int total; 20 sscanf(buf, "%d", &total); 21 fclose(f); 22 return total; 23 } 24 25 void save_new_value(int new_value) { 26 FILE *f; 27 f = fopen(PREV_FILE_LOC, "w"); 28 fprintf(f, "%d", new_value); 29 fclose(f); 30 } 31 32 int main() { 33 int previous_value = get_previous_value(); 34 35 FILE *f; 36 f = fopen(BYTES_FILE_LOC, "r"); 37 char buf[100] = {0}; 38 fgets(buf, 100, f); 39 fclose(f); 40 41 int total; 42 sscanf(buf, "%d", &total); 43 44 int total_since_last = total - previous_value; 45 46 double mebibytes = (double)total_since_last/(double)1048576/(double)2; 47 48 if (mebibytes < 10) { 49 printf("%0.2f MiB/s\n", mebibytes); 50 } 51 else { 52 printf("%0.1f MiB/s\n", mebibytes); 53 } 54 55 save_new_value(total); 56 }