Last active
April 15, 2016 05:53
-
-
Save kaitoy/c75837d3537303b004506d3e335eac17 to your computer and use it in GitHub Desktop.
Packet capture with Pcap4J in Groovy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
def filter | |
if (args) { | |
filter = args[0] | |
} | |
def nif = new NifSelector().selectNetworkInterface() | |
if (!nif) { | |
System.exit 1 | |
} | |
def handle = nif.openLive 65536, PromiscuousMode.PROMISCUOUS, 10 | |
if (filter) { | |
handle.setFilter filter, BpfCompileMode.OPTIMIZE | |
} | |
def printPacket = { packet -> | |
println "A packet captured at ${handle.getTimestamp()}:" | |
println packet | |
} | |
def listener = new PacketListener() { | |
void gotPacket(Packet packet) { | |
printPacket packet | |
} | |
} | |
handle.loop 5, listener |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment