Skip to content

Instantly share code, notes, and snippets.

@kaitoy
Last active October 3, 2019 02:13
Show Gist options
  • Save kaitoy/074769880c7bf4c0628c1c25a724c1a7 to your computer and use it in GitHub Desktop.
Save kaitoy/074769880c7bf4c0628c1c25a724c1a7 to your computer and use it in GitHub Desktop.
Packet capture with Pcap4J in Kotlin
import org.pcap4j.core.BpfProgram.BpfCompileMode
import org.pcap4j.core.NotOpenException
import org.pcap4j.core.PacketListener
import org.pcap4j.core.PcapHandle
import org.pcap4j.core.PcapNativeException
import org.pcap4j.core.PcapNetworkInterface
import org.pcap4j.core.PcapNetworkInterface.PromiscuousMode
import org.pcap4j.core.PcapStat
import org.pcap4j.packet.Packet
import org.pcap4j.util.NifSelector
fun PcapHandle.printLoop(count: Int) {
loop(count, {packet: Packet ->
println("A packet captured at ${getTimestamp()}:")
println(packet)
})
}
fun main(args: Array<String>) {
val filter = if (args.size != 0) args[0] else null
val nif = NifSelector().selectNetworkInterface()
nif ?: System.exit(1)
val handle = nif.openLive(65536, PromiscuousMode.PROMISCUOUS, 10)
filter?.let {
if (filter.length != 0) {
handle.setFilter(filter, BpfCompileMode.OPTIMIZE)
}
}
handle.printLoop(count = 5)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment