Filter by TCP and port, using the BerkeleyPacketFilter
Having problem converting the code on tutorial from Pcap.net. Need to be able to filter packets by TCP and insert port value. I am not able to understand the BerkeleyPacketFilter syntax.
//choose port
Console.WriteLine("Choose port nr");
string portnr = Console.ReadLine();
int port = Int32.Parse(portnr);
// Compile the filter
using (BerkeleyPacketFilter filter = communicator.CreateFilter(port))
{
// Set the filter
communicator.SetFilter(filter);
What is the syntax inside communicator.CreateFilter(how to insert the int port)): I have also done the following:
IpV4Datagram ip = packet.Ethernet.IpV4;
TcpDatagram tcp = ip.Tcp;
this with the PcapDotNet.Packets.Transport.TransportDatagram
If the page in the Pcap.Net User Guide giving an example of how to use the BerkeleyPacketFilter class is to be believed, the
CreateFilter
method does NOT take an integer as an argument, it takes a string as an argument.This should not be surprising, given that the documentation for the underlying libpcap/WinPCAP API for processing packet filters shows that
pcap_compile()
takes a string as an argument, and that the documentation for the format for filters indicates that a filter is a string.If you want a string that matches a given TCP port number, the string is "tcp port N", where N is the port number. You'd have to either take
port
, convert it to a string, and concatenate it with the string "tcp port " (complete with the blank after "port"), or just concatenate theportnr
string with "tcp port ".Note that you must also NEVER assume that
communicator.CreateFilter()
will succeed. I don't see any on-line documentation for Pcap.Net, so I don't know whether theCreateFilter
method will throw an exception for an invalid filter expression or not.