netspeeds.c 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. /* See LICENSE file for copyright and license details. */
  2. #include <stdio.h>
  3. #include <limits.h>
  4. #include "../util.h"
  5. #if defined(__linux__)
  6. const char *
  7. netspeed_rx(const char *interface)
  8. {
  9. static int valid;
  10. static unsigned long long rxbytes;
  11. unsigned long oldrxbytes;
  12. extern const unsigned int interval;
  13. char path[PATH_MAX];
  14. oldrxbytes = rxbytes;
  15. snprintf(path, sizeof(path), "/sys/class/net/%s/statistics/rx_bytes", interface);
  16. if (pscanf(path, "%llu", &rxbytes) != 1) {
  17. return NULL;
  18. }
  19. if (!valid) {
  20. valid = 1;
  21. return NULL;
  22. }
  23. return fmt_scaled((rxbytes - oldrxbytes) / interval * 1000);
  24. }
  25. const char *
  26. netspeed_tx(const char *interface)
  27. {
  28. static int valid;
  29. static unsigned long long txbytes;
  30. unsigned long oldtxbytes;
  31. extern const unsigned int interval;
  32. char path[PATH_MAX];
  33. oldtxbytes = txbytes;
  34. snprintf(path, sizeof(path), "/sys/class/net/%s/statistics/tx_bytes", interface);
  35. if (pscanf(path, "%llu", &txbytes) != 1) {
  36. return NULL;
  37. }
  38. if (!valid) {
  39. valid = 1;
  40. return NULL;
  41. }
  42. return fmt_scaled((txbytes - oldtxbytes) / interval * 1000);
  43. }
  44. #elif defined(__OpenBSD__)
  45. /* unimplemented */
  46. #endif