我一直对使用SharpPcap很感兴趣,但到目前为止效果并不好。
主要问题是以下代码:

   private static void device_OnPacketArrival(object sender, CaptureEventArgs packet)
   {
        if(packet is TCPPacket)
        {
            DateTime time = packet.Timeval.Date;
            int len = packet.PcapHeader.len;

            TCPPacket tcp = (TCPPacket)packet;
            string srcIp = tcp.SourceAddress;
            string dstIp = tcp.DestinationAddress;
            int srcPort = tcp.SourcePort;
            int dstPort = tcp.DestinationPort;

            Console.WriteLine("{0}:{1}:{2},
                {3} Len={4} {5}:{6} -> {7}:{8}",
                time.Hour, time.Minute, time.Second,
                time.Millisecond, len, srcIp, srcPort,
                dstIp, dstPort);
        }
    }

“类型或命名空间tcppacket可以
找不到“
好吧,我想一定是Tcpacket?-但后来出现了这个错误:
“给定的表达式从来不是
提供(“packetdotnet.tcppacket”)
“类型”
忽略这一点:
“'sharpcpap.captureEventArgs'不
包含“timeval”的定义,以及
没有扩展方法“timeval”
接受类型为的第一个参数
“sharpcpap.captureEventArgs”可以是
发现“
等等,等等。所以我的问题是,我是否遗漏了什么?
我有packetdotnet和sharppcap库,并添加了这两个using语句。
解决方案:
packet pack=packet.parsePacket(packet.packet);
tcppacket tcppacket=tcppacket.getEncapsulated(包);
    DateTime time = packet.Packet.Timeval.Date;
    int len = packet.Packet.Data.Length;

    if (tcpPacket != null)
    {
        IpPacket ipPacket = (IpPacket)tcpPacket.ParentPacket;


            IPAddress srcIp = ipPacket.SourceAddress;
            IPAddress dstIp = ipPacket.DestinationAddress;
            ushort srcPort = tcpPacket.SourcePort;
            ushort dstPort = tcpPacket.DestinationPort;

            MessageBox.Show(String.Format("{0}:{1}:{2},{3} Len={4} {5}:{6} -> {7}:{8}",
                                time.Hour, time.Minute, time.Second, time.Millisecond, len,
                                srcIp, srcPort, dstIp, dstPort)
                );
    }

最佳答案

解决方案:

Packet pack = Packet.ParsePacket(packet.Packet);
TcpPacket tcpPacket = TcpPacket.GetEncapsulated(pack);

DateTime time = packet.Packet.Timeval.Date;
int len = packet.Packet.Data.Length;

if (tcpPacket != null)
{
    IpPacket ipPacket = (IpPacket)tcpPacket.ParentPacket;


        IPAddress srcIp = ipPacket.SourceAddress;
        IPAddress dstIp = ipPacket.DestinationAddress;
        ushort srcPort = tcpPacket.SourcePort;
        ushort dstPort = tcpPacket.DestinationPort;

        MessageBox.Show(String.Format("{0}:{1}:{2},{3} Len={4} {5}:{6} -> {7}:{8}",
                            time.Hour, time.Minute, time.Second, time.Millisecond, len,
                            srcIp, srcPort, dstIp, dstPort)
            );
}

09-25 17:19