Using Libpcap I am trying to filter the Packet at word level. E.g I want to drop the packet if it has word "Hello".
How will I write the expression for that???
Using Libpcap I am trying to filter the Packet at word level. E.g I want to drop the packet if it has word "Hello".
How will I write the expression for that???
I think I already answered you on the jNetPcap forum but just to make sure, I will also post my answer here on SO.
Basically here are several ways this filtering could be done. Since you didn't specify how exactly you want to "filter", I will describe a way with a low level capture filter and a filter in java.
If you only need to look at the tcp payload and know the offset at which "Hello" should appear, I would try the capture filter generator from Wireshark at https://www.wireshark.org/tools/string-cf.html - This allows you to create a string matching capture filter for the tcp payload.
In your example (assuming tcp payload offset of 0) the capture filter (in bpf syntax) would look like:
not (tcp[((tcp[12:1] & 0xf0) >> 2):4] = 0x48656c6c && tcp[((tcp[12:1] & 0xf0) >> 2) + 4:1] = 0x6f)
Read the explanation on the linked page to know what exactly is going on. Note: I have added the "not" because we want to drop packets that match this filter and not the other way around.
You can use this filter in jNetPcap via setFilter(PcapBpfProgram bpf)
on the Pcap object.
If you don't want to restrict yourself to the tcp payload and a fixed offset, you can't use capture filters and need to filter this packets in java code.
One example would be this simple jnetpcap packet handler:
public class PacketHandler implements PcapPacketHandler<Object> {
@Override
public void nextPacket(PcapPacket packet, Object unused) {
StringBuilder str = new StringBuilder();
/*
Convert the whole packet (headers + payloads) to a string.
Adjust the first and last parameter if you don't want to look at the whole packet
*/
packet.getUTF8String(0, str, packet.getTotalSize());
String rawStringData = str.toString();
if (rawStringData.contains("Hello")) {
// we have found a packet that contains the text "Hello"
return; // ignore it
}
// do something with the packet that does not contain "Hello"
}
}
[...]
// use packet handler
pcap.loop(numberOfPackets, new PacketHandler(), null);
You could also try the method getUTF8Char(index)
if you know the starting offset of "Hello" and don't want to convert the whole packet or payload to a String.