P
P
Pcap
Search…
Opening an adapter and capturing the packets
Obtain a packet capture handle (Pcap) with a specific network interface (adapter) to look at packets on the network and process it with Pcap.loop(int, PacketHandler, T args).
Once the adapter is opened, the capture can be started with Pcap.dispatch(int, PacketHandler, T args) or Pcap.dispatch(int, PacketHandler, T args). These two functions are very similar, the difference is that Pcap.dispatch(int, PacketHandler, T args) returns (although not guaranteed) when the timeout expires while Pcap.loop(int, PacketHandler, T args) doesn't return until maximum packets have been captured, so it can block for an arbitrary period on an under-utilized network.
Java
Kotlin
Scala
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())) {
try {
pcap.loop(
10,
(args, header, buffer) -> {
System.out.println("Args : " + args);
System.out.println("Header : " + header);
System.out.println("Packet : " + buffer);
},
"Hello pcap!");
} catch (BreakException e) {
System.err.println(e.getMessage());
} catch (ErrorException e) {
System.err.println(e.getMessage());
}
}
}
fun main() {
val service = Service.Creator.create("PcapService")
val pcap = service.live(service.interfaces(), DefaultLiveOptions())
try {
pcap.loop(
10,
{ args: String, header: PacketHeader, buffer: PacketBuffer ->
println("Args : $args")
println("Header : $header")
println("Packet : $buffer")
},
"Hello pcap!"
)
} catch (e: BreakException) {
System.err.println(e.message)
} catch (e: ErrorException) {
System.err.println(e.message)
}
pcap.close()
}
def main(_args: Array[String]): Unit = {
val service = Service.Creator.create("PcapService")
val pcap = service.live(service.interfaces().next(), new DefaultLiveOptions())
try pcap.loop(10, (args: String, header: PacketHeader, buffer: PacketBuffer) => {
println("Args : ", args)
println("Header : ", header)
println("Packet : ", buffer)
}, "Hello pcap!")
catch {
case e: BreakException =>
System.err.println(e.getMessage)
case e: ErrorException =>
System.err.println(e.getMessage)
}
pcap.close()
}
Copy link