netmonitor.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /* Show the board's netlog stream (UDP, default port 19290) on the host: the
  2. * network equivalent of `make monitor`.
  3. *
  4. * netmonitor [port]
  5. *
  6. * Prints one line per datagram with a timestamp, so it plays well with
  7. * `make netmon | tee board.log`.
  8. */
  9. #include <arpa/inet.h>
  10. #include <netinet/in.h>
  11. #include <stdio.h>
  12. #include <stdlib.h>
  13. #include <string.h>
  14. #include <sys/socket.h>
  15. #include <time.h>
  16. #include <unistd.h>
  17. #define DEF_PORT 19290
  18. int main(int argc, char **argv)
  19. {
  20. unsigned int port = DEF_PORT;
  21. struct sockaddr_in addr;
  22. unsigned char buf[4096];
  23. int fd, on = 1;
  24. if (argc > 2) {
  25. fprintf(stderr, "usage: %s [port]\n", argv[0]);
  26. return 2;
  27. }
  28. if (argc == 2)
  29. port = (unsigned int)strtoul(argv[1], NULL, 0);
  30. fd = socket(AF_INET, SOCK_DGRAM, 0);
  31. if (fd < 0) {
  32. perror("socket");
  33. return 1;
  34. }
  35. setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
  36. memset(&addr, 0, sizeof(addr));
  37. addr.sin_family = AF_INET;
  38. addr.sin_addr.s_addr = htonl(INADDR_ANY);
  39. addr.sin_port = htons((uint16_t)port);
  40. if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) != 0) {
  41. perror("bind");
  42. return 1;
  43. }
  44. fprintf(stderr, "netmonitor: listening on UDP %u (Ctrl-C to exit)\n", port);
  45. for (;;) {
  46. struct sockaddr_in from;
  47. socklen_t fromlen = sizeof(from);
  48. ssize_t n = recvfrom(fd, buf, sizeof(buf) - 1, 0,
  49. (struct sockaddr *)&from, &fromlen);
  50. time_t now;
  51. struct tm tm;
  52. char stamp[16];
  53. const char *ip;
  54. unsigned int i;
  55. if (n < 0)
  56. continue;
  57. buf[n] = '\0';
  58. now = time(NULL);
  59. localtime_r(&now, &tm);
  60. strftime(stamp, sizeof(stamp), "%H:%M:%S", &tm);
  61. ip = inet_ntoa(from.sin_addr);
  62. /* Prefix the first line; keep continuation lines readable. */
  63. printf("[%s %s] ", stamp, ip);
  64. for (i = 0; i < (unsigned int)n; i++) {
  65. putchar(buf[i]);
  66. if (buf[i] == '\n' && i + 1 < (unsigned int)n)
  67. printf("[%s %s] ", stamp, ip);
  68. }
  69. if (n == 0 || buf[n - 1] != '\n')
  70. putchar('\n');
  71. fflush(stdout);
  72. }
  73. }