libcap (also: pcap) is a network traffic packet capture library that enables real-time and offline packet capture and analysis. Packet capture and analysis has many use cases.

Scala Native is an ahead-of-time compiler for Scala targeting LLVM and so capable of producing native binaries. This brings the promise of high performance coding using existing Scala skills and high quality tooling such as SBT (Scala Build Tool) and ScalaTest as well as availability of patterns like type classes.

Scala, which runs on the JVM, can interact with native libraries in two ways: JNA (Java Native Access) and JNI (Java Native Interface). JNA slower but easier than JNI. For JNA you need nothing more than a dependency but for JNI you need to write native code. When doing in Scala, you can benefit from the sbt-jni plugin that automates this compilation. Scala Native's interop is similar to JNA.

Pcap4j is an actively maintained library that wraps libpcap using JNA. Then there is jNetPcap which as a project appears inactive and uses JNI and ByteBuffer. And a last way would be to use JNI with Unsafe for the highest performance. The performance is difference is huge. There may be other even higher performance ways, but this is beyond the scope - if you have ideas do let me know on Twitter.

Packets can be captured in live mode using tcpdump, replayed with tcpreplay and visually analysed with Wireshark. libpcap supports live capture and reading from files.

libpcap flow involving data copy from kernel to user space

In live capture mode, the Kernel will look for the next packet at the pcap_next call, pass through any defined filters, and then copy the data into user-space.

There are solutions for pure zero-copy approach but it's beyond the scope of this article.