You are on page 1of 3

#include #include #include #include #include #include

<stdio.h> <stdlib.h> <sys/time.h> <sys/types.h> <unistd.h> <sys/socket.h>

/* Returns 1 if a key was hit */ int kb_hit(void) { fd_set rfds; struct timeval tv; int ret; /* Watch stdin (fd 0) to see when it has input. */ FD_ZERO(&rfds); FD_SET(0, &rfds); /* Wait a millisecond */ tv.tv_sec = 0; tv.tv_usec = 1000; ret = select(1, &rfds, NULL, NULL, &tv); if (ret == -1) { perror("Error! select()"); exit(EXIT_FAILURE); } if (FD_ISSET(0, &rfds)) { /* key was hit and data is available now */ return 1; } /* No key press within a millisecond */ return 0;

int get_char() { int buf[1]; ssize_t ret; ret = read(0, (void *)buf, 1); if (ret == -1) { perror("Error! read()"); exit(EXIT_FAILURE); } if (ret == 0) { return EOF; } return *buf; } void show_buffer(unsigned char *buf, int len) { int i, j; char str[17];

str[16] = 0; printf("\n"); for (i = 0; i < len; i += 16) { fprintf(stdout, " "); for (j = 0; j < 16 && i+j < len; j++) { fprintf(stdout, "%02x ", buf[i+j]); if (buf[i+j] > 32 && buf[i+j] < 127) str[j] = buf[i+j]; else str[j] = '.'; } for (; j < 16; j++) { fprintf(stdout, " ", buf[i+j]); str[j] = ' '; } printf(" | %s |\n", str); } fflush (stdout); } int main() { int i, ch, len, factor; unsigned char *buf; if (! kb_hit()) { printf("Error:\n" " You should pipe data to this program.\n"); exit(EXIT_FAILURE); } ch = get_char(); while (ch != EOF) { /* Read packet length */ factor = 10000; len = 0; for(i = 0; i < 5 && ch != EOF; i++) { ch = (unsigned char)ch - 48; len += (ch * factor); factor /= 10; ch = get_char(); if (ch == EOF) break; } buf = (unsigned char *) malloc(len); /* Read packet data */ for(i = 0; i < len && ch != EOF; i++) { buf[i] = ch; ch = get_char(); if (ch == EOF) break; } show_buffer(buf, len); free(buf); }

return(EXIT_SUCCESS);

You might also like