Getting Started Capturing the packets without the callback Handling a callback is sometimes not practical, it often makes the program more complex. So we need an alternative method to capture the packets without a callback.
Note: Both "PacketHeader" and "PacketBuffer" is not freed by the caller, and not guaranteed to be valid after the next call. If you needs it to remain valid, you must make a copy of it.
Docs: libpcap , javadoc .
Java Kotlin Scala Clojure
Copy public static void main(String[] _args)
throws ErrorException, PermissionDeniedException, PromiscuousModePermissionDeniedException,
TimestampPrecisionNotSupportedException, RadioFrequencyModeNotSupportedException,
NoSuchDeviceException, ActivatedException, InterfaceNotUpException,
InterfaceNotSupportTimestampTypeException {
var service = Service.Creator.create("PcapService");
try (var pcap = service.live(service.interfaces(), new DefaultLiveOptions())) {
PacketHeader header = pcap.allocate(PacketHeader.class);
PacketBuffer buffer = pcap.allocate(PacketBuffer.class);
for (int i = 0; i < 10; i++) {
try {
pcap.nextEx(header, buffer);
System.out.println("Header : " + header);
System.out.println("Packet : " + buffer);
} catch (BreakException e) {
System.err.println(e.getMessage());
} catch (TimeoutException e) {
System.err.println(e.getMessage());
}
}
}
}
Copy fun main() {
val service = Service.Creator.create("PcapService")
val pcap = service.live(service.interfaces(), DefaultLiveOptions())
pcap.setFilter("icmp", true)
val header = pcap.allocate(PacketHeader::class.java)
val buffer = pcap.allocate(PacketBuffer::class.java)
for (i in 0..9) {
try {
pcap.nextEx(header, buffer)
println("Header : $header")
println("Packet : $buffer")
} catch (e: BreakException) {
System.err.println(e.message)
} catch (e: TimeoutException) {
System.err.println(e.message)
}
}
pcap.close()
}
Copy def main(_args: Array[String]): Unit = {
val service = Service.Creator.create("PcapService")
val pcap = service.live(service.interfaces(), new DefaultLiveOptions())
val header = pcap.allocate(classOf[PacketHeader])
val buffer = pcap.allocate(classOf[PacketBuffer])
for (i <- 0 until 10) {
try {
pcap.nextEx(header, buffer)
System.out.println("Header : " + header)
System.out.println("Packet : " + buffer)
} catch {
case e: BreakException =>
System.err.println(e.getMessage)
case e: TimeoutException =>
System.err.println(e.getMessage)
case e: ErrorException =>
System.err.println(e.getMessage)
}
}
pcap.close()
}
Copy (defn -main
[& args]
(def service (. Service$Creator (create "PcapService")))
(def pcap (.live service (.interfaces service) (DefaultLiveOptions.)))
(def header (.allocate pcap pcap.spi.PacketHeader))
(def buffer (.allocate pcap pcap.spi.PacketBuffer))
(dotimes [n 10]
(.nextEx pcap header buffer)
(println header)
(println buffer))
(.close pcap))