Advertisement
Guest User

Untitled

a guest
Jun 1st, 2021
433
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.96 KB | None | 0 0
  1. /*
  2. # hexnow
  3.  
  4. intially used to monitor nc output, converting it into hex to be readable
  5.  
  6. ## future
  7.  
  8. maybe i should make it similar to xargs, so it will call xxd with the data read each time
  9. that way, the utility can be extended to do anything else
  10.  
  11. something like this:
  12. ```console
  13. $ nc -l 80 | piperead -w 16 xxd -g1 -o'{}'
  14. ```
  15.  
  16. on each call to xxd, the offset number is incremented by the number of bytes actually read. this value replaces `{}` in the command, similar to `-exec` semantics in `find`.
  17.  
  18. we can also discard the bytes and only output the accumulated number of bytes read, like this:
  19. ```console
  20. $ nc -l 80 | piperead -w 16 echo '{}'
  21. ```
  22.  
  23. while this will output the number of bytes read each time (up to a maximum of 32):
  24. ```console
  25. $ nc -l 80 | piperead -w 32 wc -c
  26. ```
  27. */
  28.  
  29. #include <stdio.h>
  30. #include <unistd.h>
  31. #include <fcntl.h>
  32. #include <stdlib.h>
  33. #include <sys/time.h>
  34. #include <sys/types.h>
  35. #include <errno.h>
  36.  
  37. #define MAX_BYTES 16
  38.  
  39. int main() {
  40.   unsigned char buf[MAX_BYTES];
  41.   unsigned char asciibuf[MAX_BYTES+1];
  42.  
  43.   int flags = fcntl(STDIN_FILENO, F_GETFL);
  44.   if (flags < 0) perror("fcntl F_GETFL");
  45.   if (fcntl(STDIN_FILENO, F_SETFL, flags | O_NONBLOCK) < 0) perror("fcntl F_SETFL");
  46.  
  47.   unsigned bytes_printed = 0;
  48.   fd_set fd_read, fd_save;
  49.   FD_ZERO(&fd_save);
  50.   FD_SET(STDIN_FILENO, &fd_save);
  51.   fd_read = fd_save;
  52.   while (select(STDIN_FILENO+1, &fd_read, NULL, NULL, NULL) > 0) {
  53.     if (FD_ISSET(STDIN_FILENO, &fd_read)) {
  54.       int len = read(STDIN_FILENO, buf, sizeof(buf));
  55.       if (len < 0) perror("read");
  56.       if (len == 0) break;
  57.       printf("%08x:", bytes_printed);
  58.       for (int i = 0; i < len; ++i) printf(" %02X", buf[i]);
  59.       for (int i = 0; i < MAX_BYTES-len; ++i) printf("   ");
  60.       for (int i = 0; i < len; ++i) asciibuf[i] = isprint(buf[i]) ? buf[i] : '.';
  61.       asciibuf[len] = '\0';
  62.       printf("  %s\n", asciibuf);
  63.       bytes_printed += len;
  64.       fd_read = fd_save;
  65.     }
  66.   }
  67. }
  68.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement