Search code examples
c#winpcapsharppcap

How to set a filter to get "Modbus/TCP" data in SharpPcap?


I am using SharpPcap.

In Wireshark, I can set the filter as mbtcp or modbus and tcp, and it works well.

In SharpPcap, if the filter is set as mbtcp or modbus and tcp, an exception

SharpPcap.PcapException:“syntax error”

will happen. I have make sure I type the string correctly.

So, how to set the filter to get all Modbus/TCP data?


Solution

  • But I want a solution

    You found a solution - "tcp port 502".

    In Wireshark, I can set the filter as mbtcp or modbus and tcp, and it works well.

    That's a Wireshark packet-matching expression, usually called a "display filter" (although it can also be used, for example, in coloring rules, which aren't filters). Those are processed by code in Wireshark, which is based on Wireshark's packet-dissection engine, so they work in programs that use that engine (such as Wireshark and TShark) and won't work in code that doesn't have Wireshark's packet-dissection engine.

    In SharpPcap, if the filter is set as mbtcp or modbus and tcp, an exception

    SharpPcap.PcapException:“syntax error”
    

    will happen. I have make sure I type the string correctly.

    SharpPcap isn't code that has Wireshark's packet-dissection engine, it's a library that's a C# wrapper for libpcap. This means that, in SharpPcap, that filter is a libpcap filter, which is written in libcpap filter syntax, which is not the same as Wireshark packet-matching expression syntax, and is not as powerful as that syntax.

    There is no simple way to incorporate Wireshark's packet-dissection engine into programs, so your best choice here is either 1) to use Wireshark rather than your program or 2) to use "tcp port 502" as your filter.