Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- # hexnow
- intially used to monitor nc output, converting it into hex to be readable
- ## future
- maybe i should make it similar to xargs, so it will call xxd with the data read each time
- that way, the utility can be extended to do anything else
- something like this:
- ```console
- $ nc -l 80 | piperead -w 16 xxd -g1 -o'{}'
- ```
- 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`.
- we can also discard the bytes and only output the accumulated number of bytes read, like this:
- ```console
- $ nc -l 80 | piperead -w 16 echo '{}'
- ```
- while this will output the number of bytes read each time (up to a maximum of 32):
- ```console
- $ nc -l 80 | piperead -w 32 wc -c
- ```
- */
- #include <stdio.h>
- #include <unistd.h>
- #include <fcntl.h>
- #include <stdlib.h>
- #include <sys/time.h>
- #include <sys/types.h>
- #include <errno.h>
- #define MAX_BYTES 16
- int main() {
- unsigned char buf[MAX_BYTES];
- unsigned char asciibuf[MAX_BYTES+1];
- int flags = fcntl(STDIN_FILENO, F_GETFL);
- if (flags < 0) perror("fcntl F_GETFL");
- if (fcntl(STDIN_FILENO, F_SETFL, flags | O_NONBLOCK) < 0) perror("fcntl F_SETFL");
- unsigned bytes_printed = 0;
- fd_set fd_read, fd_save;
- FD_ZERO(&fd_save);
- FD_SET(STDIN_FILENO, &fd_save);
- fd_read = fd_save;
- while (select(STDIN_FILENO+1, &fd_read, NULL, NULL, NULL) > 0) {
- if (FD_ISSET(STDIN_FILENO, &fd_read)) {
- int len = read(STDIN_FILENO, buf, sizeof(buf));
- if (len < 0) perror("read");
- if (len == 0) break;
- printf("%08x:", bytes_printed);
- for (int i = 0; i < len; ++i) printf(" %02X", buf[i]);
- for (int i = 0; i < MAX_BYTES-len; ++i) printf(" ");
- for (int i = 0; i < len; ++i) asciibuf[i] = isprint(buf[i]) ? buf[i] : '.';
- asciibuf[len] = '\0';
- printf(" %s\n", asciibuf);
- bytes_printed += len;
- fd_read = fd_save;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement