开发者

Packet Logging with Pcap for C#

I'm currently using the pcap library for C# and was wondering if there were any built in functions to remove the IP开发者_运维知识库 headers and the TCP/UDP/ECT headers? If not, could anyone post how they achieved removing such headers?


Are you using PacketXLib? I've used this before and found it easy enough to code with. Extracting the headers is simple enough by just knowing the basic fundamentals of the protocols

public const int ETHERNETLEN = 14;    // length of ethernet header
public const int IPLEN = 20;          // length of ip header
public const int TCPLEN = 20;         // length of tcp header

Assuming you're using the same library I did, you can then just bypass the headers to get to the raw data

int dataOffset = ETHERNETLEN + IPLEN + TCPLEN;
string rawData = "";
// Throw all the data into a string first up so we can work with it easier
for (int i = dataOffset; i < aPacket.DataSize; i++)
{
  byte nByte = (byte)aPacket.DataArray.GetValue(i);
  rawData += Convert.ToChar(nByte);
}

The code I'm looking at where I did this is probably nearly a year old though, so a bit hazy on what exactly I was doing. I was doing some http-packet reconstruction as can be seen in this question I posted. Actually, looking at that thread, it was well over a year ago when I was doing this!


I'm the author of SharpPcap, a pcap wrapper/library for c#.

If you were using SharpPcap, SharpPcap breaks the packet down into datagrams. So you'd end up with an EthernetPacket that contained an IpPacket that contained say a UdpPacket. If you wanted just the udp packet you can easily extract that like:

Packet p = Packet.ParsePacket(rawCapture.LinkLayerType, rawCapture.Data);
var udpPacket = UdpPacket.GetEncapsulated(p);
if(udpPacket != null) { Console.WriteLine("found udp packet '{0}'", udpPacket); }

UdpPacket.GetEncapsulated() traverses the datagrams looking for the packet. Same kind of approach works for all of the types that are parsed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜