How to get data from TCPPacket using SharpPcap?

2019-06-24 07:29发布

问题:

I need small sniffer for my report so I went with C# and SharpPcap.

packet = Packet.ParsePacket(rawCapture.LinkLayerType, rawCapture.Data);
tcpPacket = TcpPacket.GetEncapsulated(packet);

I have raw packet with all packet data. Then I get Packet out of it with some info such as source/destination/protocol/etc. After that I get tcp packet out of that.

Now how do I get only actual packet data that software sent/received?

回答1:

Was simple enough.

packet.PayloadPacket.PayloadPacket.PayloadData


回答2:

tcpPacket.PayloadData or PayloadPacket should be what you want. PayloadData is valid if Packet.Net isn't aware of how to parse the data into a sub-packet, and PayloadPacket is valid if it does. I'm not sure any tcp packet parsing occurs today so you should be safe saying tcpPacket.PayloadData.

Maybe the api should be changed such that PayloadData is always the raw data in the tcp packet and PayloadPacket is null or non-null depending on whether the contents of the packet were parsed. Then you could get the contents of any packet, Ethernet, IP etc by using PayloadData. Thoughts?

You could refer to some nested PayloadPacket of 'packet' but it is difficult to know how the packet is constructed. Is it Ethernet->IP->Tcp or are there wrappers around the Ethernet packet? With TcpPacket.GetEncapsulated() these situations are handled for you.

Chris

Author of SharpPcap/Packet.Net