netspeed.c 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #include <err.h>
  2. #include <stdio.h>
  3. #include <limits.h>
  4. #include <stdint.h>
  5. #include "netspeed.h"
  6. #include "../lib/util.h"
  7. #include "../aslstatus.h"
  8. #define SYS_CLASS "/sys/class/net"
  9. #define STATISTICS(S) "statistics/" #S "_bytes"
  10. static void netspeed(char *out,
  11. const char *interface,
  12. uint32_t interval,
  13. static_data_t *static_data,
  14. const char *property);
  15. void
  16. netspeed_rx(char *out, const char *interface, uint32_t interval, void *ptr)
  17. {
  18. netspeed(out, interface, interval, ptr, STATISTICS(rx));
  19. }
  20. void
  21. netspeed_tx(char *out, const char *interface, uint32_t interval, void *ptr)
  22. {
  23. netspeed(out, interface, interval, ptr, STATISTICS(tx));
  24. }
  25. static inline void
  26. netspeed_cleanup(void *ptr)
  27. {
  28. eclose(((struct netspeed_data *)ptr)->fd);
  29. }
  30. static inline void
  31. netspeed(char *out,
  32. const char *interface,
  33. uint32_t interval,
  34. static_data_t *static_data,
  35. const char *property)
  36. {
  37. struct netspeed_data *data = static_data->data;
  38. uintmax_t oldbytes = data->bytes;
  39. char buf[JU_STR_SIZE];
  40. if (!static_data->cleanup) static_data->cleanup = netspeed_cleanup;
  41. if (!sysfs_fd_or_rewind(&data->fd, SYS_CLASS, interface, property))
  42. ERRRET(out);
  43. if (!eread(data->fd, WITH_LEN(buf))) ERRRET(out);
  44. if (!esscanf(1, buf, "%ju", &data->bytes)) ERRRET(out);
  45. if (!oldbytes) ERRRET(out);
  46. fmt_human(out, (data->bytes - oldbytes) * 1000 / interval);
  47. }