Search code examples
c#pcap.net

How do I change PCap.Net packet data?


I have a (production) WireShark capture file that I need to 'replay' over my (debug) network. I can read and interpret the packets, but I need to tweak a few details before the packets can be sent, like source IP addresses and ports.

The problem, however, is that all data in the PcapDotNet.Packets.Packet is read-only. It just has setters. So like setting for instance the Ethernet.IpV4.Source will not work.

IpV4Address.TryParse("192.168.1.10", out var newAddress); // for demo sake.
packet.Ethernet.IpV4.Source = newAddress; // Won't work

Is there a simple way to avoid building a new packet from scratch, or is that the only way to create a slightly different packet?


Solution

  • Instead of changing the packet inplace, you should just create a new one based on the old one.

    You can use ExtractLayer() on each layer you want to keep from the old packet, and then change the layer properties if necessary.

    In this case, you can do:

    IpV4Layer ipV4Layer = packet.Ethernet.IpV4.ExtractLayer();
    ipV4Layer.Source = newAddress;
    
    Packet newPacket = PacketBuild.Build(DateTime.Now, packet.Ethernet.ExtractLayer(), ipV4Layer, packet.Ethernet.IpV4.Payload.ExtractLayer());
    

    You probably also want to reset the IPv4 checksum, so you should do:

    ipV4Layer.HeaderChecksum = null;
    

    And you might need to something similar to the UDP or TCP layers on top of the IPv4 layer, in case you have them.