コード例 #1
0
        // The callback function for the SharpPcap library
        private void device_PcapOnPacketArrival(object sender, CaptureEventArgs e)
        {
            Packet packet;

            try
            {
                packet = PacketDotNet.Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data);
            }
            catch (Exception ex)
            {
                //System.Console.Write(ex.Message); //todo: sometimes get error raw packet not implemented?
                return;
            }

            if (firstTimeStamp == 0)
            {
                firstTimeStamp = decimal.Parse(e.Packet.Timeval.Seconds.ToString() + "." + e.Packet.Timeval.MicroSeconds.ToString());
            }

            totalPackets++;
            UdpPacket udpPacket = (UdpPacket)packet.Extract(typeof(UdpPacket));
            if (udpPacket != null)
            {
                HandleDNS(udpPacket);
                return;
            }

            IpPacket  ipPacket  = (IpPacket)packet.Extract(typeof(IpPacket));
            TcpPacket tcpPacket = (TcpPacket)packet.Extract(typeof(TcpPacket));

            if (tcpPacket == null) return;
            totalTCPPackets++;

            Connection c = new Connection(tcpPacket);
            TcpRecon recon = null;
            curPacket = tcpPacket;
            curPacketTime = e.Packet.Timeval;

            if (!sharpPcapDict.ContainsKey(c))
            {
                c.generateFileName(outDir);
                recon = new TcpRecon(c.fileName);
                recon.LastSourcePort = tcpPacket.SourcePort;
                recon.StreamStartTimeStamp = e.Packet.Timeval.Seconds.ToString() + "." + e.Packet.Timeval.MicroSeconds.ToString();
                decimal curTime = decimal.Parse(recon.StreamStartTimeStamp);
                recon.relativeTimeStamp = (curTime - firstTimeStamp).ToString();

                sharpPcapDict.Add(c, recon);

                if (!IPExists("tcp: " + ipPacket.DestinationAddress)) ips.Add("tcp: " + ipPacket.DestinationAddress);
                if (!IPExists("tcp: " + ipPacket.SourceAddress)) ips.Add("tcp: " + ipPacket.SourceAddress);
                owner.Invoke(NewStream, recon);
            }else{
                recon = sharpPcapDict[c];
            }

            //can contain fragments and out of order packets
            recon.ReassemblePacket(ipPacket.SourceAddress.Address,
                                   ipPacket.DestinationAddress.Address,
                                   tcpPacket, e.Packet.Timeval);

            if (recon.PacketWritten) //reassembly/reordering complete data was saved this time..
            {
                if (recon.LastSourcePort != tcpPacket.SourcePort) //previous entry is now complete so lets add it.
                {
                    AddNewNode(recon);
                    recon.LastSourcePort = tcpPacket.SourcePort;
                }
            }
        }