Mark Oliver's World

Posted: 13/07/2022

Reading UDP Packets With SharpPcap

If you are intending on reading UDP packets in promiscuous mode using SharpPcap, then you need to consider the amount of traffic on the network you are going to intercept.

If you are sweeping up packets on a very busy network (think Voip network), then you will need to think about dropped packets.
UDP does not guarantee receiving the packet, so if a NIC is overloaded, then it will simply discard the UDP packets.

On top of that, when processing packets using SharpPcap, you need to read the packets and process them as fast as they are being received, or again you will drop packets.

SharpPcap can help us here, we can reduce the number of dropped packets by using its buffering mechanisms.

Instead of something like:

            var deviceConfig = new DeviceConfiguration {      Mode = DeviceModes.Promiscuous,      ReadTimeout = DeviceReadTimeout};  device.Open(deviceConfig);
            
          

We can instead use something like:

            const int buffersize = 10 * 1024 * 1024;//10MB  var deviceConfig = new DeviceConfiguration {      BufferSize = buffersize, //This means we favour keeping the packets over dropping them, by using more RAM     KernelBufferSize = buffersize,      Mode = DeviceModes.Promiscuous,      ReadTimeout = DeviceReadTimeout};  device.Open(deviceConfig);
            
          

This will tell SharpPcap to use 10MB of RAM to buffer incoming data before it drops packets.
This will give you more time to process the large number of packets before packet loss.

This however is not a panacea to slow code, and you should consider why you are not processing the packets fast enough in the first place.


Thanks for reading this post.

If you want to reach out, catch me on Twitter!

I am always open to mentoring people, so get in touch.