7

I need to save UDP packets to a file and would like to use the pcap format to reuse the various tools available (wireshark, tcpdump, ...). There are some information in this thread but I can't find how to write the global file header 'struct pcap_file_header'.

pcap_t* pd = pcap_open_dead(DLT_RAW, 65535);
pcap_dumper_t* pdumper = pcap_dump_open(pd, filename);

struct pcap_file_header file_hdr;
file_hdr.magic_number = 0xa1b2c3d4;
file_hdr.version_major = 2;
file_hdr.version_minor = 4;
file_hdr.thiszone = 0;
file_hdr.sigfigs = 0;
file_hdr.snaplen = 65535;
file_hdr.linktype = 1;

// How do I write file_hdr to m_pdumper?

while( (len = recvmsg(sd, &msg_hdr, 0)) > 0 )
  pcap_dump((u_char*)m_pdumper, &m_pcap_pkthdr, (const u_char*)&data);

How should I write the global file header? If there is no specific pcap function available, how can I retrieve the file descriptor to insert the header using write()?

Community
  • 1
  • 1
Robert Kubrick
  • 8,413
  • 13
  • 59
  • 91

2 Answers2

6

You shouldn't need to write that header, pcap_open_dead should do it for you. You only need to fill out and write that header yourself if you want to write the file directly instead of using pcap_dump and friends. There's an example here of a trivial program write out a pcap file with those functions.


original answer, concerning writing the file directly:

I can't remember exactly how this works, but I wrote a patch to redir a while ago that would write out pcap files, you may be able to use it as an example.

You can find it attached to this debian bug. (bug link fixed.)

Some of it is for faking the ethernet and IP headers, and may not be applicable as you're using pcap_dump_open and pcap_dump where as the patch linked above writes out the pcap file without using any libraries, but I'll leave this here anyway in case it helps.

Ted Feng
  • 829
  • 1
  • 17
  • 22
je4d
  • 7,628
  • 32
  • 46
  • Thanks, but it looks like you have done everything using regular file write() calls. I am using pcap_dump() and can't figure where to get the file descriptor. – Robert Kubrick Apr 11 '12 at 21:11
  • @RobertKubrick Updated above. I've left the original answer since even with `pcap_dump` you'll still need to fake an IP header, and the patch linked above may help with that. – je4d Apr 11 '12 at 21:22
  • True, no need to write the global file header, I just verified. – Robert Kubrick Apr 11 '12 at 21:37
  • use pcap_fileno() to get a file descriptor from a pcap_t*. You can however call pcap_dump() directly to write packets to a pcap_t – nos Oct 25 '12 at 07:49
0

If you are interested in UDP and TCP only, you should use DLT_EN10MB instead of DLT_RAW ( cf pcap_open_dead to simulate full UDP packets capture ).

It is much better when editing in WireShak.

Community
  • 1
  • 1
poukill
  • 540
  • 8
  • 18