libpcap or PF_PACKET?

2019-03-31 13:39发布

问题:

I understand this question has been discussed many times: Should I use libpcap or PF_PACKET (the data link socket) to capture packets?

Based on my research, libpcap is suggested over PF_PACKET almost everywhere, mainly due to its portability.

However, for my current project (which is used in a production system), portability is not a concern at all, all I care about is performance (speed, packet loss ratio). My program is running on CentOS 5.10 (kernel 2.6.18) As far as I know, libpcap put a timestamp on each packet. Does this cause big performance loss? Are there other factors that make libpcap unsuitable in a high-speed network?

回答1:

As far as I know, libpcap put a timestamp on each packet.

No, libpcap gets a timestamp for the packet from the OS packet capture mechanism that it uses - which, on Linux is...

...PF_PACKET sockets.

The Linux kernel time stamps incoming packets. PF_PACKET sockets have multiple ways of reading from them:

  • regular socket receives, for which you can either get a time stamp with an explicit ioctl (so you can avoid fetching it to userland, but you can't avoid the kernel time stamping the packet in the first place; libpcap, when using regular socket receives, always asks for the time stamp);
  • memory-mapped access, which always supplies the time stamp.

Libpcap uses memory-mapped access whenever it's available; if you care about capture performance, you probably want to do so as well. It's not easy to use, however.