在jNetpcap中,有三种loop函数。
<T> int loop(int cnt, JBufferHandler<T> handler, T user)
<T> int loop(int cnt, JPacketHandler<T> handler, T user)
<T> int loop(int cnt, PcapPacketHandler<T> handler, T user)
因此有三种包处理函数的形式(winpcap只有一种):
class MyJBufferHandler<T> implements JBufferHandler<T>
{
public void nextPacket(PcapHeader header, JBuffer buffer, T user)
{
Timestamp timestamp =new Timestamp(header.timestampInMillis());
System.out.printf("Received packet at %s caplen=%-4d len=%-4d %s\n",
timestamp.toString(), // timestamp to 1 ms accuracy
header.caplen(), // Length actually captured
header.wirelen(), // Original length of the packet
user // User supplied object
);
}
}
class MyJPacketHandler<T> implements JPacketHandler<T>
{
public void nextPacket(JPacket packet, T user)
{
final JCaptureHeader header = packet.getCaptureHeader();
System.out.printf("Packet caplen=%d wirelen=%d\n", header.caplen(),header.wirelen());
/*
* For packets, generate output using an internal TextFormatter that
* sends output to a StringBuilder, then calls on its toString() method
* to generate the final string which is returned and send to
* System.out.
*
* Alternative would be to send output directly to System.out, bypassing
* any intermediate string:
*
* JFormatter out = new TextFormatter(); // output to System.out
* out.format(packet); // Format and send output to System.out
*
* Or to generate XML output:
*
* PrintStream outputstream = // My output stream
* JFormatter out = next XmlFormatter(outputstream);
* out.format(packet);
*/
System.out.println(packet.toString());
}
}
class MyPcapPcaketHandler<T> implements PcapPacketHandler<T>
{
public void nextPacket(PcapPacket packet, T user)
{
System.out.printf("Received packet at %s caplen=%-4d len=%-4d %s\n",
new Date(packet.getCaptureHeader().timestampInMillis()),
packet.getCaptureHeader().caplen(), // Length actually captured
packet.getCaptureHeader().wirelen(), // Original length
user // User supplied object
);
}