Пример #1
0
        public static void Main(string[] args)
        {
            // Print SharpPcap version
            string ver = SharpPcap.Version.VersionString;
            Console.WriteLine("SharpPcap {0}, Example8.ReadFile.cs\n", ver);

            Console.WriteLine();

            // read the file from stdin or from the command line arguments
            string capFile;
            if(args.Length == 0)
            {
                Console.Write("-- Please enter an input capture file name: ");
                capFile = Console.ReadLine();
            } else
            {
                // use the first argument as the filename
                capFile = args[0];
            }

            Console.WriteLine("opening '{0}'", capFile);

            ICaptureDevice device;

            try
            {
                // Get an offline device
                device = new OfflineCaptureDevice( capFile );

                // Open the device
                device.Open();
            } 
            catch(Exception e)
            {
                Console.WriteLine("Caught exception when opening file" + e.ToString());
                return;
            }

            //Register our handler function to the 'packet arrival' event
            device.OnPacketArrival += 
                new PacketArrivalEventHandler( device_OnPacketArrival );

            Console.WriteLine();
            Console.WriteLine
                ("-- Capturing from '{0}', hit 'Ctrl-C' to exit...",
                capFile);

            // Start capture 'INFINTE' number of packets
            // This method will return when EOF reached.
            device.Capture();

            // Close the pcap device
            device.Close();
            Console.WriteLine("-- End of file reached.");
            Console.Write("Hit 'Enter' to exit...");
            Console.ReadLine();
        }
Пример #2
0
        /// <summary>
        /// Basic capture example
        /// </summary>
        public static void Main(string[] args)
        {
            // Print SharpPcap version
            string ver = SharpPcap.Version.VersionString;
            Console.WriteLine("SharpPcap {0}, Example10.SendQueues.cs\n", ver);

            Console.Write("-- Please enter an input capture file name: ");
            string capFile = Console.ReadLine();

            ICaptureDevice device;

            try
            {
                // Get an offline file pcap device
                device = new OfflineCaptureDevice(capFile);

                // Open the device for capturing
                device.Open();
            } 
            catch(Exception e)
            {
                Console.WriteLine(e.Message);
                return;
            }

            Console.Write("Queueing packets...");

            //Allocate a new send queue
            var squeue = new WinPcap.SendQueue
                ( (int)((OfflineCaptureDevice)device).FileSize );
            RawCapture packet;
            
            try
            {
                //Go through all packets in the file and add to the queue
                while((packet = device.GetNextPacket()) != null )
                {
                    if( !squeue.Add( packet ) )
                    {
                        Console.WriteLine("Warning: packet buffer too small, "+
                            "not all the packets will be sent.");
                        break;
                    }
                }
            }
            catch(Exception e)
            {
                Console.WriteLine(e.Message);
                return;
            }

            Console.WriteLine("OK");

            Console.WriteLine();
            Console.WriteLine("The following devices are available on this machine:");
            Console.WriteLine("----------------------------------------------------");
            Console.WriteLine();

            int i=0;

            var devices = LibPcap.LibPcapLiveDeviceList.Instance;
            /* Scan the list printing every entry */
            foreach(var dev in devices)
            {
                /* Description */
                Console.WriteLine("{0}) {1} {2}", i, dev.Name, dev.Description);
                i++;
            }

            Console.WriteLine();
            Console.Write("-- Please choose a device to transmit on: ");
            i = int.Parse( Console.ReadLine() );
            devices[i].Open();
            string resp;

            if(devices[i].LinkType != device.LinkType)
            {
                Console.Write("Warning: the datalink of the capture" +
                    " differs from the one of the selected interface, continue? [YES|no]");
                resp = Console.ReadLine().ToLower();

                if((resp!="")&&( !resp.StartsWith("y")))
                {
                    Console.WriteLine("Cancelled by user!");
                    devices[i].Close();
                    return;
                }
            }

            // close the offline device
            device.Close();

            // find the network device for sending the packets we read
            device = devices[i];

            Console.Write("This will transmit all queued packets through"+
                " this device, continue? [YES|no]");
            resp = Console.ReadLine().ToLower();

            if((resp!="") && ( !resp.StartsWith("y")))
            {
                Console.WriteLine("Cancelled by user!");
                return;
            }

            try
            {
                var winPcapDevice = device as WinPcap.WinPcapDevice;

                Console.Write("Sending packets...");
                int sent = winPcapDevice.SendQueue(squeue, WinPcap.SendQueueTransmitModes.Synchronized);
                Console.WriteLine("Done!");
                if( sent < squeue.CurrentLength )
                {
                    Console.WriteLine("An error occurred sending the packets: {0}. "+
                        "Only {1} bytes were sent\n", device.LastError, sent);
                }
            }
            catch(Exception e)
            {
                Console.WriteLine( "Error: "+e.Message );
            }

            //Free the queue
            squeue.Dispose();
            Console.WriteLine("-- Queue is disposed.");
            //Close the pcap device
            device.Close();
            Console.WriteLine("-- Device closed.");
            Console.Write("Hit 'Enter' to exit...");
            Console.ReadLine();
        }
Пример #3
0
        /// <summary>
        /// Parse packet capture (.pcap) file and create statistics output (.csv).
        /// </summary>
        /// <param name="filename">Packet capture (.pcap) file</param>
        /// <param name="outputFoldername">Folder to write output (.csv) file</param>
        static void parsePcap(string filename, DirectoryInfo outputFolder)
        {
            OfflineCaptureDevice pcapfile = new OfflineCaptureDevice(filename);

            pcapfile.Open();

            // Create a statistics file in the output statistics folder
            string shortname = System.IO.Path.GetFileNameWithoutExtension(pcapfile.Name);


            string netCsvFilename =
                outputFolder.FullName + "\\" +
                shortname +
                "-net.csv";

            string appCsvFilename =
                outputFolder.FullName + "\\" +
                shortname +
                "-app.csv";

            // It is possible that the pcap file is in use by another thread
            // This can be detected by checking to see if the .csv file exists
            // Return and find another pcap if it does

            if (File.Exists(netCsvFilename))
            {
                return;
            }
            if (File.Exists(appCsvFilename))
            {
                return;
            }

            // Create stream writers for the output

            StreamWriter netCsvWriter = new StreamWriter(netCsvFilename);

            netCsvWriter.WriteLine("Pcap,DateStamp,TimeIndex,srcMAC,dstMAC,srcIP,srcIPstr,dstIP,dstIPstr,srcPORT,dstPORT,Type,Bytes,AppBytes");

            StreamWriter appCsvWriter = new StreamWriter(appCsvFilename);

            appCsvWriter.WriteLine("Pcap,DateStamp,TimeIndex,srcMAC,dstMAC,srcIP,srcIPstr,dstIP,dstIPstr,value1,value2,value3,value4");

            // Loop thru the packets and record the statistics

            RawCapture next = null;

            while (true)
            {
                try
                {
                    if ((next = pcapfile.GetNextPacket()) == null)
                    {
                        break;
                    }
                }
                catch
                {
                    continue;
                }

                // TCP/IP Communications

                string srcMACstr = "unknown"; // Hexadecimal string
                string srcIP     = "";
                string srcIPstr  = "";        // Hexadecimal string
                int    srcPort   = 0;

                string dstMACstr = "unknown"; // Hexadecimal string
                string dstIP     = "";
                string dstIPstr  = "";        // Hexadecimal string
                int    dstPort   = 0;

                DateTime time          = next.Timeval.Date;
                Int64    linkByteCount = 0;
                Int64    appByteCount  = 0;
                int      itype         = 0;
                string   appLayerStats = "";

                // Ethernet packets

                if (next.LinkLayerType != LinkLayers.Ethernet)
                {
                    continue;
                }

                if (next.Data.Length < 20)
                {
                    continue;
                }

                Packet         link     = null;
                EthernetPacket ethernet = null;

                try
                {
                    link     = Packet.ParsePacket(LinkLayers.Ethernet, next.Data);
                    ethernet = (EthernetPacket)link;
                }
                catch
                {
                    continue;
                }

                srcMACstr = ethernet.SourceHwAddress.ToString();
                dstMACstr = ethernet.DestinationHwAddress.ToString();


                linkByteCount = link.Bytes.Length;

                if (link.PayloadPacket is IpPacket)
                {
                    IpPacket ip = (IpPacket)link.PayloadPacket;

                    srcIP    = ip.SourceAddress.ToString();
                    srcIPstr = SimWitty.Library.Core.Encoding.Base16.ToBase16String(ip.SourceAddress.GetAddressBytes());

                    dstIP    = ip.DestinationAddress.ToString();
                    dstIPstr = SimWitty.Library.Core.Encoding.Base16.ToBase16String(ip.DestinationAddress.GetAddressBytes());

                    if (ip.PayloadPacket is TcpPacket)
                    {
                        TcpPacket tcp = (TcpPacket)ip.PayloadPacket;
                        srcPort       = tcp.SourcePort;
                        dstPort       = tcp.DestinationPort;
                        appByteCount  = tcp.PayloadData.Length;
                        itype         = 1;
                        appLayerStats = ApplicationLayerHandling(itype, dstPort, tcp.PayloadData);
                    }

                    if (ip.PayloadPacket is UdpPacket)
                    {
                        UdpPacket udp = (UdpPacket)ip.PayloadPacket;
                        srcPort      = udp.SourcePort;
                        dstPort      = udp.DestinationPort;
                        appByteCount = udp.PayloadData.Length;
                        itype        = 2;
                    }
                }
                // "Pcap,DateStamp,TimeIndex,srcMAC,dstMAC,srcIP,srcIPstr,dstIP,dstIPstr,srcPORT,dstPORT,Type,Bytes,AppBytes"
                netCsvWriter.WriteLine("{0},{1} {2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14}",
                                       shortname,
                                       time.ToShortDateString(),
                                       time.ToLongTimeString(),
                                       time.Hour + "_" + time.Minute,
                                       srcMACstr,
                                       dstMACstr,
                                       srcIP,
                                       srcIPstr,
                                       dstIP,
                                       dstIPstr,
                                       srcPort,
                                       dstPort,
                                       itype.ToString(),
                                       linkByteCount.ToString(),
                                       appByteCount.ToString()
                                       );

                // "Pcap,DateStamp,TimeIndex,srcMAC,srcMACstr,dstMAC,dstMACstr,srcIP,srcIPstr,dstIP,dstIPstr,value1,value2,value3,value4"
                if (appLayerStats.Length != 0)
                {
                    appCsvWriter.WriteLine("{0},{1} {2},{3},{4},{5},{6},{7},{8},{9},{10}",
                                           shortname,
                                           time.ToShortDateString(),
                                           time.ToLongTimeString(),
                                           time.Hour + "_" + time.Minute,
                                           srcMACstr,
                                           dstMACstr,
                                           srcIP,
                                           srcIPstr,
                                           dstIP.ToString(),
                                           dstIPstr,
                                           appLayerStats);
                }
            }

            // Close the output
            netCsvWriter.Flush();
            netCsvWriter.Close();
            appCsvWriter.Flush();
            appCsvWriter.Close();

            // Close the pcap device
            pcapfile.Close();

            // The pause that refreshes
            System.Threading.Thread.Sleep(1000);
        }