2

I'm using SharpPcap to capture packets.

I'm trying to get Traffic Class value and I'm using udp.ipv6.TrafficClass.ToString().

the problem that I'm getting this exception:

Object reference not set to an instance of an object.

private void packetCapturingThreadMethod()
{

   Packet packet = null;

   while ((packet = device.GetNextPacket()) != null)
   {
        packet = device.GetNextPacket();

        if (packet is UDPPacket)
        {
            UDPPacket udp = (UDPPacket)packet;

            MessageBox.Show(udp.ipv6.TrafficClass.ToString());
        }
   }
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
Eyla
  • 5,751
  • 20
  • 71
  • 116

2 Answers2

4

What I think is happening here is that you're actually only checking every other packet.

You don't need the second packet = device.GetNextPacket(); because packet is already being assigned at the top of your while loop.

Try this and see if you still get an exception:

private void packetCapturingThreadMethod()
{

   Packet packet = null;

   while ((packet = device.GetNextPacket()) != null)
   {
        if (packet is UDPPacket)
        {
            UDPPacket udp = (UDPPacket)packet;

            MessageBox.Show(udp.ipv6.TrafficClass.ToString());
        }
   }
}


If you're still getting an exception then it's most likely because you're not getting a valid ipv6 packet.

Ad Hoc
  • 333
  • 2
  • 9
3

That exception means that either udp, udp.ipv6 or udp.ipv6.TrafficClass is null. You need to check:

if (udp != null && udp.ipv6 != null && udp.ipv6.TrafficClass != null)
{
    MessageBox.Show(udp.ipv6.TrafficClass.ToString();
}
John Saunders
  • 160,644
  • 26
  • 247
  • 397
  • Good answer. If SharpPcap can't parse something it automatically returns null. Ex, if you capture a TCP packet and try to parse it as UDP you'll get back null. Make sure you're filters are set correctly, then check the packets being captured for null before you parse the payload/header/fields to avoid any exceptions. – Evan Plaice Nov 10 '10 at 07:09