SharpPcap - 从数据包中提取信息的数据包捕获问题

时间:2010-04-21 18:53:21

标签: c# packet-capture sharppcap

我正在使用SharpPcap捕获数据包。

我正在尝试获取流量类值,而我正在使用udp.ipv6.TrafficClass.ToString()。

我遇到这个例外的问题:

对象引用未设置为对象的实例。

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());
        }
   }
}

2 个答案:

答案 0 :(得分:4)

我认为这里发生的事实是你实际上只是检查所有其他数据包。

您不需要第二个packet = device.GetNextPacket();,因为已经在while循环的顶部分配了packet

试试这个,看看你是否还有异常:

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());
        }
   }
}


如果您仍然遇到异常,那么很可能是因为您没有获得有效的ipv6数据包。

答案 1 :(得分:3)

该异常意味着udpudp.ipv6udp.ipv6.TrafficClass为空。你需要检查:

if (udp != null && udp.ipv6 != null && udp.ipv6.TrafficClass != null)
{
    MessageBox.Show(udp.ipv6.TrafficClass.ToString();
}