-1

I was creating a simple sniffer, just for fun, and I want to output the dump to a file. Here's the code of the sniffer:

#include <stdio.h>
#include <pcap.h>

#define MAX_PACKET_NUM 5

int main(void) {

    struct pcap_pkthdr header;
    const u_char *packet;
    char errbuf[PCAP_ERRBUF_SIZE];
    char *device;
    pcap_t *pcap_handle;
    int i;

    printf("## Now sniffing on: %s ##\n", device);
    printf("## Max packets number for this session: %d\n", MAX_PACKET_NUM);

    printf("[?] Sniffing...\n");

    pcap_handle = pcap_open_live(device, 1000, 1, 0, errbuf);

    for(i=0; i < MAX_PACKET_NUM; i++) {
        packet = pcap_next(pcap_handle, &header);
        printf("[!] Captured a %d bytes packet!\n", header.len);
        dump(packet, header.len);
    }
}

It works fine, but how can I output the dump to a file? I tried using file streams, but I don't really know how to output a function. As you can see, the dump() function prints the output on the screen, maybe there is a function to output to a file? Please help me out guys!

Benoît Guédas
  • 801
  • 7
  • 25
jndok
  • 859
  • 3
  • 12
  • 28

2 Answers2

3

You are looking for fprintf function. Use fopen to open the file, fprintf to write to the file and at the end fclose to close the file.

ouah
  • 134,166
  • 14
  • 247
  • 314
  • Yes, I tried with those, but how I can write a function with them? They only accept strings or numbers as parameters and I don't know how to store the dump in a string... – jndok Feb 24 '13 at 13:05
  • @jndok You simply have to replace your `printf` calls with `fprintf` calls in your program. – ouah Feb 24 '13 at 13:06
0

If your sniffer runs from the command line on some version of UN*X or on Windows, and if it "prints the output to the screen" by using, for example, printf() (rather than fprintf()), then what it really does is print its output to the "standard output".

In that case, you can, on both UN*X and Windows, send the output to a file by "redirecting" the standard output to a file; this would be done with

mysniffer {command-line arguments} > {pathname to the file}