network.c (1155B)
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/wlx3460f9198188/statistics/tx_bytes" 6 #else 7 #define PREV_FILE_LOC "/tmp/network_down_previous" 8 #define BYTES_FILE_LOC "/sys/class/net/wlx3460f9198188/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 if (f == NULL) { 38 printf("0.00 MiB/s\n"); 39 return 0; 40 } 41 42 char buf[100] = {0}; 43 fgets(buf, 100, f); 44 fclose(f); 45 46 int total; 47 sscanf(buf, "%d", &total); 48 49 int total_since_last = total - previous_value; 50 51 double mebibytes = (double)total_since_last/(double)1048576/(double)2; 52 53 if (mebibytes < 10) { 54 printf("%0.2f MiB/s\n", mebibytes); 55 } 56 else { 57 printf("%0.1f MiB/s\n", mebibytes); 58 } 59 60 save_new_value(total); 61 }