0

I tried running this code, but nothing is ever shown. (Yes, I ran it as root) If I can't get ngrep's output I guess I'll try to figure out how to use libpcap with c++ although I haven't been able to find any good examples.

int main(void)
{
    FILE* fproc = popen("ngrep -d wlan0 GET");
    char c;
    do {
        printf("%c", fgetc(fproc));
    } while (c!=EOF);
}

So what about this code causes nothing to be show, and what do you suggest to easily parse ngrep's output, or some other way of capturing GET requests, maybe with libpcap

Gene Bushuyev
  • 5,512
  • 20
  • 19

1 Answers1

1

I see the possible potential problems:

  1. You have no open mode for the popen call? Leaving this off is likely to result in either a core dump or a random value of the stack deciding whether it's a read or write pipe.

  2. The c variable should be an int rather than a char since it has to be able to hold all characters plus an EOF indicator.

  3. And, you're not actually assigning anything to c which would cause the loop to exit.

  4. With that do loop, you're trying to output the EOF to the output stream at the end. Don't know off the top of my head if this is a bad thing but it's certainly not necessary.

Try this:

int main(void) {
    int ch;
    FILE* fproc;

    if ((fproc = popen("ngrep -d wlan0 GET", "r")) < 0) {
        fprintf (stderr, "Cannot open pipe\n");
        return 1;
    }

    while ((ch = fgetc (fproc)) != EOF) {
        printf ("%c", ch);
    };

    pclose (fproc);

    return 0;
}

You should also be aware that the pipe is fully buffered by default so you may not get any information until the buffer is full.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • "You should also be aware that the pipe is fully buffered by default so you may not get any information until the buffer is full." How can I get each character as it is output by ngrep? Instantly, not having to wait for the buffer to be full. –  Jun 22 '11 at 16:50