static void Main(string[] args) { //var hex = ""; if (args.Length != 1) { Console.WriteLine("usage: " + Environment.GetCommandLineArgs()[0] + " <filename>"); return; } // Create the offline device OfflinePacketDevice selectedDevice = new OfflinePacketDevice(args[0]); // Open the capture file using (PacketCommunicator communicator = selectedDevice.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000)) { communicator.SetFilter("tcp"); // start the capture var i = 0; communicator.ReceiveSomePackets(out i, 1000, PacketHandler); Console.WriteLine(i); //communicator.ReceivePackets(0, PacketHandler); } /*string docHeader = "25504446"; * string docFooter = "0D0A2525454F460D0A"; * int pFrom = hex.IndexOf(docHeader) + docHeader.Length; * int pTo = hex.LastIndexOf(docFooter); * String result2 = hex.Substring(pFrom, pTo - pFrom);*/ }
static void Main(string[] args) { // Send anonymous statistics about the usage of Pcap.Net PcapDotNet.Analysis.PcapDotNetAnalysis.OptIn = true; // Check command line if (args.Length != 1) { Console.WriteLine("usage: " + Environment.GetCommandLineArgs()[0] + " <filename>"); return; } // Create the offline device OfflinePacketDevice selectedDevice = new OfflinePacketDevice(args[0]); // Open the capture file using (PacketCommunicator communicator = selectedDevice.Open(65536, // portion of the packet to capture // 65536 guarantees that the whole packet will be captured on all the link layers PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode 1000)) // read timeout { // Read and dispatch packets until EOF is reached communicator.ReceivePackets(0, DispatcherHandler); } }
public static void Test_ReadPacketsFromDumpFile_01() { // from project ReadingPacketsFromADumpFile _tr.WriteLine("Test_ReadPacketsFromDumpFile_01"); string dumpFile = @"dump\dump.pcap"; dumpFile = GetPath(dumpFile); _tr.WriteLine("read packets from dump file \"{0}\"", dumpFile); // Create the offline device OfflinePacketDevice device = new OfflinePacketDevice(dumpFile); __communicator = null; //_rs.OnAbortExecution += new OnAbortEvent(OnAbortExecution); _rs.OnAbortExecution = OnAbortExecution; try { // Open the capture file using (__communicator = device.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000)) { // Read and dispatch packets until EOF is reached __communicator.ReceivePackets(0, ReadPacketsFromDumpFile); } } finally { //_rs.OnAbortExecution -= new OnAbortEvent(OnAbortExecution); } }
public void ReadDumpFile(string path) { // Opens device OfflinePacketDevice device = new OfflinePacketDevice(path); using (PacketCommunicator communicator = device.Open(0x10000, PacketDeviceOpenAttributes.Promiscuous, 1000)) { //communicator.SetFilter("ip and tcp"); //communicator.ReceivePackets(0, DispatcherHandler); Packet packet; communicator.ReceivePacket(out packet); while (packet != null) { if (IsHttpRequest(packet)) { HttpRequestDatagram request = packet?.Ethernet?.Ip?.Tcp?.Http as HttpRequestDatagram; ParseHttpRequest(request); } // Gets next packet communicator.ReceivePacket(out packet); } } }
/// <summary> /// Retrieve details about a packet /// </summary> /// <param name="index">Index of the packet to retrieve</param> /// <param name="ctrl">UI elements</param> public static void RetrievePacketDetails(int index, object[] ctrl) { // Create the off-line device OfflinePacketDevice selectedDevice = new OfflinePacketDevice(detailsFile); // Open the capture file using (PacketCommunicator communicator = selectedDevice.Open(65536, // portion of the packet to capture // 65536 guarantees that the whole packet will be captured on all the link layers PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode 1000)) // read timeout { Packet packet = null; try { while (index-- > 0) { communicator.ReceivePacket(out packet); } } catch (Exception) { return; } PacketParser.ParsePacket(packet, ctrl); } }
/// <summary> /// Start an off-line capture /// </summary> /// <param name="file">The dump file name to capture</param> /// <param name="callback">Callback to handle packets</param> /// <param name="IsBadDumpFile">Flag indicates whether the dump file is invalid</param> public static void StartOfflineCapture(string file, HandlePacket callback, ref bool IsBadDumpFile) { PacketCommunicator pc = communicator; try { // Create the off-line device OfflinePacketDevice selectedDevice = new OfflinePacketDevice(file); communicator = selectedDevice.Open(65536, // portion of the packet to capture // 65536 guarantees that the whole packet will be captured on all the link layers PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode 1000); // read timeout // Compile the filter using (BerkeleyPacketFilter filter = communicator.CreateFilter(SnifferConfig.Filter.FilterString)) { communicator.SetFilter(filter); } // Read and dispatch packets until EOF is reached communicator.ReceivePackets(0, callback); } catch (Exception) { IsBadDumpFile = true; } finally { if (pc != null) { communicator = pc; } } }
// Long time operation public void Load(string filepath) { // file validation if (!Path.GetExtension(filepath).Equals(".pcap", StringComparison.OrdinalIgnoreCase)) { throw new ArgumentException("The file is nonexist or not valid"); } Reset(); dev = new OfflinePacketDevice(filepath); FileInfo info = new FileInfo(filepath); totalbytes = info.Length; ReportProgress(ProgressSource.Load, Prog_ReadFileStart, "读取文件..."); // Read all packets from file until EOF using (PacketCommunicator communicator = dev.Open()) { communicator.ReceivePackets(0, OnPacketArrival); } ReportProgress(ProgressSource.Load, Prog_SortPacketsStart, "对数据包排序..."); plist.Sort(); ReportProgress(ProgressSource.Load, Prog_AnalyzePacketsStart, "分析中..."); Analyze(); fileLoaded = true; ReportProgress(ProgressSource.Load, 100, "完成"); }
private async Task LoadFile() { var file = txtPath.Text; if (!File.Exists(file)) { throw new Exception("File not found - " + file); } Log("Loading packets from file " + file); var dumpFile = new OfflinePacketDevice(file); var packets = new List <Packet>(); await Task.Run(() => { using (var communicator = dumpFile.Open(65536, PacketDeviceOpenAttributes.None, 1000)) { while (true) { try { communicator.ReceivePacket(out var packet); if (packet == null) { break; } packets.Add(packet); } catch (Exception e) { Log(e); } } } _packets = packets.Select((p, i) => new PacketInfo { Num = i + 1, TimeStamp = p.Timestamp, Length = p.Length, Kind = p.DataLink.Kind, Protocol = GetPacketProto(p).ToString(), Packet = p }).ToArray(); }); lstPackets.SetObjects(_packets); lstPackets.AutoResizeColumns(); lstPackets.CalculateReasonableTileSize(); SetColumnWidth("Length", 80); }
public void ReadNonExistingUnicodeFilenameTest() { const string ReadUnicodeFilename = "abc_non_existing_\u00F9_\u05D0\u05D1\u05D2.pcap"; OfflinePacketDevice device = new OfflinePacketDevice(ReadUnicodeFilename); using (PacketCommunicator communicator = device.Open()) { Assert.Fail(); } }
public static void Parse(string fileName, Action <Packet> handler) { // Create the offline device OfflinePacketDevice selectedDevice = new OfflinePacketDevice(fileName); // Open the capture file using (PacketCommunicator communicator = selectedDevice.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000)) { // Read and dispatch packets until EOF is reached communicator.ReceivePackets(0, new HandlePacket(handler)); } }
// Long time operation public void TcpStreamReassemble(string saveDir) { if (!fileLoaded) { throw new InvalidOperationException("No file has been loaded"); } ReportProgress(ProgressSource.TCPReassemble, 0, "分析中..."); using (TcpReassemble tcpre = new TcpReassemble()) { // Save complete connections to files ConnectionToFile ctf = new ConnectionToFile(saveDir); tcpre.ConnectionFinished += (o, e) => ctf.Save(e.Connection); int cnt = 0; // Read all packets from file until EOF using (PacketCommunicator communicator = dev.Open()) { communicator.SetFilter("tcp"); communicator.ReceivePackets(0, p => { tcpre.AddPacket(p.Ethernet.IpV4); ReportProgress(ProgressSource.TCPReassemble, (int)((double)cnt / plist.Count), string.Format("分析中...{0}/{1}", ++cnt, plist.Count)); }); } } ReportProgress(ProgressSource.TCPReassemble, 100, "完成...打开文件夹..."); // Open folder System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo() { UseShellExecute = true, FileName = saveDir, Verb = "open" }); }
public SY_Sort_PCap(String path) { OfflinePacketDevice selectedDevice = new OfflinePacketDevice(path); list = new List <SY_Sort_PCap>(); // Open the capture file using (PacketCommunicator communicator = selectedDevice.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000)) { // Read and dispatch packets until EOF is reached communicator.ReceivePackets(0, DispatcherHandler); } }
public WiresharkFile(string filepath) { FileName = filepath; PacketCount = 0; TimePacketCount = 0; FileInfo file = new FileInfo(filepath); FileSizeKB = file.Length / 1000; FileCreatedOn = file.CreationTime.ToString(); FileEstTime = 0; // Create the offline device OfflineDevice = new OfflinePacketDevice(filepath); // Count packets using (PacketCommunicator communicator = OfflineDevice.Open(65536, // portion of the packet to capture // 65536 guarantees that the whole packet will be captured on all the link layers PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode 1000)) // read timeout { // Read and dispatch packets until EOF is reached communicator.ReceivePackets(0, ProcessNewFilePackets); } // Estimate time using (PacketCommunicator communicator = OfflineDevice.Open(65536, // portion of the packet to capture // 65536 guarantees that the whole packet will be captured on all the link layers PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode 1000)) // read timeout { // Read and dispatch packets until EOF is reached communicator.ReceivePackets(0, EstimateTime); } Common.ConsoleWriteLine(ConsoleText); Common.ConsoleWriteLine(ConsoleText, "File Loaded: " + FileName.Substring(FileName.LastIndexOf("\\") + 1) + "\n - SIP Packets = " + SIP_Packets + "\n - RTP Packets = " + RTP_Packets); }
public static void ReconstructSingleFileSharpPcap(string capFile) { //PcapDevice device; PacketDevice device; //FileInfo fi = new FileInfo(capFile); var fi = zFile.CreateFileInfo(capFile); _path = fi.DirectoryName + "\\"; try { //Get an offline file pcap device //device = SharpPcap.GetPcapOfflineDevice(capFile); device = new OfflinePacketDevice(capFile); //Open the device for capturing //device.PcapOpen(); using (PacketCommunicator communicator = device.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000)) { communicator.ReceivePackets(0, device_PcapOnPacketArrival); } } catch (Exception e) { Console.WriteLine(e.Message); return; } //Register our handler function to the 'packet arrival' event //device.PcapOnPacketArrival += new SharpPcap.PacketArrivalEvent(device_PcapOnPacketArrival); // FOR THIS LINE TO WORK YOU NEED TO CHANGE THE // SHARPPCAP LIBRARY MANUALLY AND REMOVE PcapSetFilter method // FROM PcapOfflineDevice // // add a filter so we get only tcp packets // device.PcapSetFilter("tcp"); //Start capture 'INFINTE' number of packets //This method will return when EOF reached. //device.PcapCapture(SharpPcap.INFINITE); //Close the pcap device //device.PcapClose(); // Clean up foreach (TcpRecon tr in sharpPcapDict.Values) { tr.Close(); } sharpPcapDict.Clear(); }
static void Main(string[] args) { List <string> wordlis = LoadWordList(); // Create the offline device OfflinePacketDevice selectedDevice = new OfflinePacketDevice("03.cap"); // Open the capture file using (PacketCommunicator communicator = selectedDevice.Open(65536, // portion of the packet to capture // 65536 guarantees that the whole packet will be captured on all the link layers PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode 1000)) // read timeout { // Read and dispatch packets until EOF is reached communicator.ReceivePackets(0, DispatcherHandler); } byte[] apMac = GetPortion(fourWayHandShake[0], 4, 6); byte[] stMac = GetPortion(fourWayHandShake[0], 10, 6); byte[] aNonce = GetPortion(fourWayHandShake[0], 51, 32); byte[] sNonce = GetPortion(fourWayHandShake[1], 51, 32); byte[] mic = GetPortion(fourWayHandShake[1], 115, 16); byte[] eapol = GetPortion(fourWayHandShake[1], 34, fourWayHandShake[1].Length - 34); for (int i = eapol.Length - 40; i < eapol.Length - 40 + 16; i++) { eapol[i] = 0; } bool isFind = false; foreach (var pass in wordlis) { Console.WriteLine(pass); byte[] pmk = CalculatePMK(Encoding.ASCII.GetBytes(pass), Encoding.ASCII.GetBytes("k_and_s")); byte[] ptk = CalculatePTK(pmk, stMac, apMac, sNonce, aNonce); if (PtkIsValid(ptk, eapol, mic)) { Console.WriteLine("Key Found ({0})", pass); isFind = true; break; } } if (!isFind) { Console.WriteLine("Key Not Found"); } }
public void ParsePacket(string filePath) { OfflinePacketDevice selectedDevice = new OfflinePacketDevice(filePath); using (PacketCommunicator communicator = selectedDevice.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000)) { try { communicator.ReceivePackets(0, AnalyzeCurrentPacket); } catch { } } var AnalyzedSession = CombineOpenCloseSessions(); }
static void Main(string[] args) { if (FileCheck(fileName)) { PacketDevice selectedDevice = new OfflinePacketDevice(fileName); // Open the device using (PacketCommunicator communicator = selectedDevice.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000)) { communicator.ReceivePackets(0, PacketHandler); } } Console.WriteLine(arr); Console.ReadLine(); }
public static void Read(string file) { var selectedDevice = new OfflinePacketDevice(file); // Open the capture file using (PacketCommunicator communicator = selectedDevice.Open(65536, // portion of the packet to capture // 65536 guarantees that the whole packet will be captured on all the link layers PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode 1000)) // read timeout { communicator.SetFilter("tcp port 1119 and ip net "+ GameServerRange); // Read and dispatch packets until EOF is reached communicator.ReceivePackets(0, DispatcherHandler); } }
public static void Read(string file) { var selectedDevice = new OfflinePacketDevice(file); // Open the capture file using (PacketCommunicator communicator = selectedDevice.Open(65536, // portion of the packet to capture // 65536 guarantees that the whole packet will be captured on all the link layers PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode 1000)) // read timeout { communicator.SetFilter("tcp port 1119 and ip net " + GameServerRange); // Read and dispatch packets until EOF is reached communicator.ReceivePackets(0, DispatcherHandler); } }
public MessageBoxResult Send(string PcapPath, PacketDevice Nic) { try { var capLength = new FileInfo(PcapPath).Length; var selectedPcap = new OfflinePacketDevice(PcapPath); using (var inputCommunicator = selectedPcap.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000)) { using (var outputCommunicator = Nic.Open(100, PacketDeviceOpenAttributes.Promiscuous, 1000)) { using (var sendBuffer = new PacketSendBuffer((uint)capLength)) { var numPackets = 0; var falsePackets = 0; Packet packet; while (inputCommunicator.ReceivePacket(out packet) == PacketCommunicatorReceiveResult.Ok) { if ((packet.Count > 1514)) { ++falsePackets; } else { sendBuffer.Enqueue(packet); ++numPackets; } } outputCommunicator.Transmit(sendBuffer, false); return(MessageBox.Show(numPackets.ToString() + " " + "Packets were sent successfully,\n" + falsePackets.ToString() + " " + "Packets weren't sent successfully,\n" + " Would you like to exit?", "Success", MessageBoxButton.YesNo)); } } } } catch (System.ArgumentException) { return(MessageBox.Show("User Must Choose a file")); } catch (System.InvalidOperationException) { return(MessageBox.Show("Wrong File, only .pcap file supperted")); } }
private void Button_Click(object sender, RoutedEventArgs e) { // Create the offline device OfflinePacketDevice selectedDevice = new OfflinePacketDevice(System.IO.Path.Combine(inpath.Text, "SV.pcap")); // Open the capture file using (PacketCommunicator communicator = selectedDevice.Open(65536, // portion of the packet to capture // 65536 guarantees that the whole packet will be captured on all the link layers PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode 1000)) // read timeout { communicator.SetFilter("ether proto 0x88ba"); communicator.ReceivePackets(0, DispatcherHandler); } foreach (Data adata in data) { kek.Text += adata.ToString() + Environment.NewLine; } }
private static void ParseAndRead() { var device = new OfflinePacketDevice(@"C:\Users\Thomas\Desktop\dumpfile.pcap"); // Open the capture file using (PacketCommunicator communicator = device.Open(65536, // portion of the packet to capture // 65536 guarantees that the whole packet will be captured on all the link layers PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode 1000)) // read timeout { // Read and dispatch packets until EOF is reached try { communicator.ReceivePackets(0, DispatcherHandler); } catch (Exception e) { Console.WriteLine(e.Message); } } }
/// <summary> /// Tries to open packet on provided path /// </summary> /// <param name="path">Path to packet</param> /// <returns>Packet object with data</returns> public Packet TryOpenUserPacketFromFile(string path) { try { var providedPacket = new OfflinePacketDevice(path); using (PacketCommunicator communicator = providedPacket.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000)) { Packet savedPacket; communicator.ReceivePacket(out savedPacket); return(savedPacket); } } catch (InvalidOperationException ex) { Console.WriteLine(ex.Message); } return(null); }
public void start_capture(object path_to_file) { if (!(path_to_file is string)) { throw new Exception("bad type of input given"); } OfflinePacketDevice selectedDevice = new OfflinePacketDevice((string)path_to_file); using (PacketCommunicator communicator = selectedDevice.Open(65536, // portion of the packet to capture // 65536 guarantees that the whole packet will be captured on all the link layers PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode 1000)) // read timeout { Packet packet; do { PacketCommunicatorReceiveResult result = communicator.ReceivePacket(out packet); switch (result) { case PacketCommunicatorReceiveResult.Timeout: // Timeout elapsed continue; case PacketCommunicatorReceiveResult.Ok: capturedPackets.Add(CapturedPacketManager.providePacket(packet)); // PacketHandler(packet); break; case PacketCommunicatorReceiveResult.Eof: return; default: throw new InvalidOperationException("The result " + result + " shoudl never be reached here"); } } while (true); } }
private void button1_Click(object sender, EventArgs e) { openFileDialog1.FileName = "C:\\Магистратура\\1 курс 2 семестр\\СОВвИ\\CTU-13-Dataset\\CTU-13-Dataset\\2 - взял"; if (openFileDialog1.ShowDialog() == DialogResult.OK) { textBox1.Text = openFileDialog1.FileName; OfflinePacketDevice offlinePacketDevice = new OfflinePacketDevice(openFileDialog1.FileName); //offlinePacketDevice. PacketCommunicator communicator = offlinePacketDevice.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000); // read timeout //communicator.ReceivePackets(0, DispatcherHandler); //List<Packet> packets = new List<Packet>(); InfaDlyaLoadingPackets infa = new InfaDlyaLoadingPackets(); infa.communicator = communicator; Task.Factory.StartNew(() => { LoadingPackets(infa); }); //Создание и запуск нового потока /* * while (true) * { * Packet packet; * communicator.ReceivePacket(out packet); * * if (packet == null) * { * break; * } * * packets.Add(packet); * textBoxLog.Text += packets.Count; * } */ } }
static void Main(string[] args) { // Check command line if (args.Length != 1) { Console.WriteLine("usage: " + Environment.GetCommandLineArgs()[0] + " <filename>"); return; } // Create the offline device OfflinePacketDevice selectedDevice = new OfflinePacketDevice(args[0]); // Open the capture file using (PacketCommunicator communicator = selectedDevice.Open(65536, // portion of the packet to capture // 65536 guarantees that the whole packet will be captured on all the link layers PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode 1000)) // read timeout { // Read and dispatch packets until EOF is reached communicator.ReceivePackets(0, DispatcherHandler); } }
private void tbtnOpen_Click(object sender, EventArgs e) { OpenFileDialog openFileDialog1 = new OpenFileDialog(); openFileDialog1.InitialDirectory = @"C:\"; openFileDialog1.Title = "Browse Text Files"; openFileDialog1.Filter = "dump files (*.pcap)|*.pcap"; openFileDialog1.FilterIndex = 2; openFileDialog1.RestoreDirectory = true; if (openFileDialog1.ShowDialog() == DialogResult.OK) { OfflinePacketDevice selectedDevice = new OfflinePacketDevice(openFileDialog1.FileName); using (PacketCommunicator communicator = selectedDevice.Open(65536, // portion of the packet to capture // 65536 guarantees that the whole packet will be captured on all the link layers PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode 1000)) // read timeout { communicator.ReceivePackets(0, DispatcherHandler); } } }
public List <Packet> ParsePcapFile(string path) { List <Packet> list = new List <Packet>(); OfflinePacketDevice selectedDevice = new OfflinePacketDevice(path); // открытие файла для парсинга using (PacketCommunicator communicator = selectedDevice.Open(65536, // считает полностью весь пакет 65536 max size of packet PacketDeviceOpenAttributes.Promiscuous, // какие - то непонятные флаги) 1000)) // время чтения { // Установка фильтра на TCP Пакеты using (var filter = communicator.CreateFilter("ip and tcp")) { communicator.SetFilter(filter); bool endOfFile = false; // разираем полученные пакеты по одному do { PcapDotNet.Packets.Packet packet; var myPacket = new Packet(); PacketCommunicatorReceiveResult result = communicator.ReceivePacket(out packet); switch (result) { case PacketCommunicatorReceiveResult.Eof: { endOfFile = true; break; } case PacketCommunicatorReceiveResult.Timeout: break; // Timeout case PacketCommunicatorReceiveResult.Ok: { IpV4Datagram ip = packet.Ethernet.IpV4; TcpDatagram tcp = ip.Tcp; var http = packet.IpV4.Tcp.Http; var httpHeader = packet.IpV4.Tcp.Http.Header; if (!http.IsValid) { continue; } // common fields myPacket.Protocol = "HTTP"; myPacket.SourceAddress = ip.Source.ToString(); myPacket.SourcePort = tcp.SourcePort.ToString(); myPacket.DestinationAddress = ip.Destination.ToString(); myPacket.DestinationPort = tcp.DestinationPort.ToString(); myPacket.TimeStamp = packet.Timestamp; myPacket.Length = packet.Length; myPacket.Data = packet.Buffer; // unusual fields StringBuilder properties = new StringBuilder(); // Длинна заголовков if (httpHeader != null) { properties.AppendLine("HeaderLength : " + httpHeader.BytesLength.ToString()); // Длинна контента properties.AppendLine("ContentLength : " + httpHeader.ContentLength); // Тип контента properties.AppendLine("ContentType : " + httpHeader.ContentType); // Поле передачи properties.AppendLine("ContentType : " + httpHeader.Trailer.ValueString); // Шифрования properties.AppendLine("TransferEncoding : " + httpHeader.TransferEncoding.ValueString); } if (http.IsRequest && http.IsValid) { string message = http.Decode(Encoding.ASCII); if (message.StartsWith("GET ")) { properties.AppendLine("PacketType : " + "Get"); properties.AppendLine("Message : " + message); } else if (message.StartsWith("POST ")) { properties.AppendLine("PacketType : " + "Post"); properties.AppendLine("Message : " + message); } } myPacket.Header = properties.ToString(); list.Add(myPacket); continue; } default: throw new InvalidOperationException("The result " + result + " shoudl never be reached here"); } } while (!endOfFile); } } return(list); }
/// <summary> /// Retrieve details about a packet /// </summary> /// <param name="index">Index of the packet to retrieve</param> /// <param name="ctrl">UI elements</param> public static void RetrievePacketDetails(int index, object[] ctrl) { // Create the off-line device OfflinePacketDevice selectedDevice = new OfflinePacketDevice(detailsFile); // Open the capture file using (PacketCommunicator communicator = selectedDevice.Open(65536, // portion of the packet to capture // 65536 guarantees that the whole packet will be captured on all the link layers PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode 1000)) // read timeout { Packet packet = null; try { while (index-- > 0) communicator.ReceivePacket(out packet); } catch (Exception) { return; } PacketParser.ParsePacket(packet, ctrl); } }
static void Main(string[] args) { // Check the validity of the command line if (args.Length == 0 || args.Length > 2) { Usage(); return; } // Retrieve the device list from the local machine IList<LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine; if (allDevices.Count == 0) { Console.WriteLine("No interfaces found! Make sure WinPcap is installed."); return; } // Print the list for (int i = 0; i != allDevices.Count; ++i) { LivePacketDevice device = allDevices[i]; Console.Write((i + 1) + ". " + device.Name); if (device.Description != null) Console.WriteLine(" (" + device.Description + ")"); else Console.WriteLine(" (No description available)"); } int deviceIndex = 0; do { Console.WriteLine("Enter the interface number (1-" + allDevices.Count + "):"); string deviceIndexString = Console.ReadLine(); if (!int.TryParse(deviceIndexString, out deviceIndex) || deviceIndex < 1 || deviceIndex > allDevices.Count) { deviceIndex = 0; } } while (deviceIndex == 0); // Take the selected adapter PacketDevice selectedOutputDevice = allDevices[deviceIndex - 1]; // Retrieve the length of the capture file long capLength = new FileInfo(args[0]).Length; // Chek if the timestamps must be respected bool isSync = (args.Length == 2 && args[1][0] == 's'); // Open the capture file OfflinePacketDevice selectedInputDevice = new OfflinePacketDevice(args[0]); using (PacketCommunicator inputCommunicator = selectedInputDevice.Open(65536, // portion of the packet to capture // 65536 guarantees that the whole packet will be captured on all the link layers PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode 1000)) // read timeout { using (PacketCommunicator outputCommunicator = selectedOutputDevice.Open(100, PacketDeviceOpenAttributes.Promiscuous, 1000)) { // Check the MAC type if (inputCommunicator.DataLink != outputCommunicator.DataLink) { Console.WriteLine( "Warning: the datalink of the capture differs from the one of the selected interface."); Console.WriteLine("Press a key to continue, or CTRL+C to stop."); Console.ReadKey(); } // Allocate a send buffer using (PacketSendBuffer sendBuffer = new PacketSendBuffer((uint)capLength)) { // Fill the buffer with the packets from the file int numPackets = 0; Packet packet; while (inputCommunicator.ReceivePacket(out packet) == PacketCommunicatorReceiveResult.Ok) { sendBuffer.Enqueue(packet); ++numPackets; } // Transmit the queue Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); long startTimeMs = stopwatch.ElapsedMilliseconds; Console.WriteLine("Start Time: " + startTimeMs); outputCommunicator.Transmit(sendBuffer, isSync); long endTimeMs = stopwatch.ElapsedMilliseconds; Console.WriteLine("End Time: " + endTimeMs); long elapsedTimeMs = endTimeMs - startTimeMs; Console.WriteLine("Elapsed Time: " + elapsedTimeMs); double averagePacketsPerSecond = elapsedTimeMs == 0 ? double.MaxValue : (double)numPackets / elapsedTimeMs * 1000; Console.WriteLine("Elapsed time: " + elapsedTimeMs + " ms"); Console.WriteLine("Total packets generated = " + numPackets); Console.WriteLine("Average packets per second = " + averagePacketsPerSecond); Console.WriteLine(); } } } }
public List <Packet> ParsePcapFile(string path) { List <Packet> list = new List <Packet>(); OfflinePacketDevice selectedDevice = new OfflinePacketDevice(path); // открытие файла для парсинга using (PacketCommunicator communicator = selectedDevice.Open(65536, // считает полностью весь пакет 65536 max size of packet PacketDeviceOpenAttributes.Promiscuous, // флаг 1000)) // время чтения { // Установка фильтра на udp Пакеты using (var filter = communicator.CreateFilter("ip and udp")) { communicator.SetFilter(filter); bool endOfFile = false; // разираем полученные пакеты по одному do { PcapDotNet.Packets.Packet packet; var myPacket = new Packet(); PacketCommunicatorReceiveResult result = communicator.ReceivePacket(out packet); switch (result) { case PacketCommunicatorReceiveResult.Eof: { endOfFile = true; break; } case PacketCommunicatorReceiveResult.Timeout: break; // Timeout case PacketCommunicatorReceiveResult.Ok: { IpV4Datagram ip = packet.Ethernet.IpV4; UdpDatagram udp = ip.Udp; // common fields myPacket.Protocol = "UDP"; myPacket.SourceAddress = ip.Source.ToString(); myPacket.SourcePort = udp.SourcePort.ToString(); myPacket.DestinationAddress = ip.Destination.ToString(); myPacket.DestinationPort = udp.DestinationPort.ToString(); myPacket.TimeStamp = packet.Timestamp; myPacket.Length = packet.Length; myPacket.Data = packet.Buffer; // unusual fields StringBuilder properties = new StringBuilder(); // Контрольная сумма udp пакета properties.AppendLine("Checksum : " + udp.Checksum.ToString()); // Длинна(число байт) udp пакета properties.AppendLine("PacketLength : " + udp.TotalLength.ToString()); myPacket.Header = properties.ToString(); list.Add(myPacket); continue; } default: throw new InvalidOperationException("The result " + result + " shoudl never be reached here"); } } while (!endOfFile); } } return(list); }
private static void Main(string[] args) { try { // Check command line if (args.Length < 2 || args.Length > 3) { Console.WriteLine("usage: " + Environment.GetCommandLineArgs()[0] + " filename outputadapteraddress [mspergrain]"); Console.WriteLine("<hit enter to exit>"); Console.ReadLine(); return; } _outputAdapterAddress = args[1]; if (args.Length == 3) { _msPerGrain = Convert.ToInt32(args[2]); } while (_packetCount == 0) { // Create the offline device var selectedDevice = new OfflinePacketDevice(args[0]); // Create output UDP streaming client _outputClient = PrepareOutputClient("232.0.7.1", 5000); Console.WriteLine($"Sending contained packets from {args[0]} to adapter {args[1]}"); // Open the capture file using (var communicator = selectedDevice.Open(65536, // portion of the packet to capture // 65536 guarantees that the whole packet will be captured on all the link layers PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode 1000)) // read timeout { // Read and dispatch packets until EOF is reached communicator.ReceivePackets(0, DispatcherHandler); } //since we don't know the PCAP length, just read once and pre-allocate buffer; then re-read and populate buffer //lazy, inefficient - but reliable and no impact once startup complete if (_bytePayloads != null) { continue; } _bytePayloads = new byte[_packetCount][]; _packetCount = 0; } ushort seqNum = 0; var firstpacket = new RtpPacket(_bytePayloads[0]); var lastpacket = new RtpPacket(_bytePayloads[_packetCount - 1]); var timestampSpan = (int)((lastpacket.Timestamp - firstpacket.Timestamp) / 90); int timeBetweenGrains; _totalGrains = _totalGrains / 2; if (_totalGrains > 1) { timeBetweenGrains = timestampSpan / (_totalGrains - 1); } else { timeBetweenGrains = timestampSpan; } if (timeBetweenGrains == 0 && timeBetweenGrains < 0) { timeBetweenGrains = 40; } else { timeBetweenGrains = _msPerGrain; } var outputStartTime = DateTime.UtcNow.TimeOfDay.TotalMilliseconds; var loopCount = 0; var grainCount = 0; while (true) { uint currentTimestamp = 0; //repeating payload loop for (var i = 0; i < _packetCount; i++) { var packet = new RtpPacket(_bytePayloads[i]); if (currentTimestamp != packet.Timestamp) { //RTP packet timestamp has changed - will be a new frame set //how much time should have passed since playback began? var totalExpectedElapsed = grainCount * timeBetweenGrains + (loopCount * _totalGrains * timeBetweenGrains); var diffTotal = (totalExpectedElapsed + outputStartTime) - DateTime.UtcNow.TimeOfDay.TotalMilliseconds; if (diffTotal > 0) { System.Threading.Thread.Sleep((int)diffTotal); } currentTimestamp = packet.Timestamp; grainCount++; } packet.SequenceNumber = seqNum++; packet.Timestamp = (uint)(loopCount * (timeBetweenGrains * _totalGrains * 90) + (grainCount * timeBetweenGrains * 90)); var newBuf = packet.GetPacket(); _outputClient.Send(newBuf, packet.PacketSize); } loopCount++; } } catch (Exception ex) { PrintToConsole("Exception trying to play back PCAP: " + ex.Message); Console.WriteLine("<hit enter to exit>"); Console.ReadLine(); } }
static void Main(string[] args) { // Check the validity of the command line if (args.Length == 0 || args.Length > 2) { Usage(); return; } // Retrieve the device list from the local machine IList <LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine; if (allDevices.Count == 0) { Console.WriteLine("No interfaces found! Make sure WinPcap is installed."); return; } // Print the list for (int i = 0; i != allDevices.Count; ++i) { LivePacketDevice device = allDevices[i]; Console.Write((i + 1) + ". " + device.Name); if (device.Description != null) { Console.WriteLine(" (" + device.Description + ")"); } else { Console.WriteLine(" (No description available)"); } } int deviceIndex = 0; do { Console.WriteLine("Enter the interface number (1-" + allDevices.Count + "):"); string deviceIndexString = Console.ReadLine(); if (!int.TryParse(deviceIndexString, out deviceIndex) || deviceIndex < 1 || deviceIndex > allDevices.Count) { deviceIndex = 0; } } while (deviceIndex == 0); // Take the selected adapter PacketDevice selectedOutputDevice = allDevices[deviceIndex - 1]; // Retrieve the length of the capture file long capLength = new FileInfo(args[0]).Length; // Chek if the timestamps must be respected bool isSync = (args.Length == 2 && args[1][0] == 's'); // Open the capture file OfflinePacketDevice selectedInputDevice = new OfflinePacketDevice(args[0]); using (PacketCommunicator inputCommunicator = selectedInputDevice.Open(65536, // portion of the packet to capture // 65536 guarantees that the whole packet will be captured on all the link layers PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode 1000)) // read timeout { using (PacketCommunicator outputCommunicator = selectedOutputDevice.Open(100, PacketDeviceOpenAttributes.Promiscuous, 1000)) { // Check the MAC type if (inputCommunicator.DataLink != outputCommunicator.DataLink) { Console.WriteLine( "Warning: the datalink of the capture differs from the one of the selected interface."); Console.WriteLine("Press a key to continue, or CTRL+C to stop."); Console.ReadKey(); } // Allocate a send buffer using (PacketSendBuffer sendBuffer = new PacketSendBuffer((uint)capLength)) { // Fill the buffer with the packets from the file int numPackets = 0; Packet packet; while (inputCommunicator.ReceivePacket(out packet) == PacketCommunicatorReceiveResult.Ok) { sendBuffer.Enqueue(packet); ++numPackets; } // Transmit the queue Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); long startTimeMs = stopwatch.ElapsedMilliseconds; Console.WriteLine("Start Time: " + startTimeMs); outputCommunicator.Transmit(sendBuffer, isSync); long endTimeMs = stopwatch.ElapsedMilliseconds; Console.WriteLine("End Time: " + endTimeMs); long elapsedTimeMs = endTimeMs - startTimeMs; Console.WriteLine("Elapsed Time: " + elapsedTimeMs); double averagePacketsPerSecond = elapsedTimeMs == 0 ? double.MaxValue : (double)numPackets / elapsedTimeMs * 1000; Console.WriteLine("Elapsed time: " + elapsedTimeMs + " ms"); Console.WriteLine("Total packets generated = " + numPackets); Console.WriteLine("Average packets per second = " + averagePacketsPerSecond); Console.WriteLine(); } } } }
private void OpenDumpFileCommandExecuted(object sender, ExecutedRoutedEventArgs e) { var openFileDialog = new OpenFileDialog { Filter = "Pcap dump file|*.pcap", Title = "Open saved pcap dump file", FileName = "e:\\dump.pcap" }; if (openFileDialog.ShowDialog().Value) { Captured.Clear(); var selectedDevice = new OfflinePacketDevice(openFileDialog.FileName); capturedPacketsListBox.DataContext = Captured; using (var communicator = selectedDevice.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000)) { communicator.ReceivePackets(0, p => Captured.Add(p)); } e.Handled = true; } }
private void simplePacketReaderToolStripMenuItem_Click(object sender, EventArgs e) { string fname; if (openFileDialog1.ShowDialog() == DialogResult.OK) { fname = openFileDialog1.SafeFileName; greHash.Clear(); greStreamHash.Clear(); richTextBox1.Clear(); packetCount = 0; mplsPackets = 0; totalMPLSBytes = 0; richTextBox1.AppendText("Open file " + openFileDialog1.FileName + "\n"); startTime = 0; lastPaketTime = 0; elapsedTime = 0; totalIPBytes = 0; totalGREBytes = 0; totalMPLSBytes = 0; OfflinePacketDevice interpreter = new OfflinePacketDevice(openFileDialog1.FileName); using (PacketCommunicator communicator = interpreter.Open(250, PacketDeviceOpenAttributes.Promiscuous, 1000)) { communicator.ReceivePackets(0, DispatchHandler); } } else { richTextBox1.AppendText("No file"); return; } float totalTime = ((lastPaketTime - startTime) / 10000000.0f); float ipbitrate = totalIPBytes * 8.0f / totalTime / 1000000.0f; float grebitrate = totalGREBytes * 8.0f / totalTime / 1000000.0f; float mplsbitrate = totalMPLSBytes * 8 / totalTime / 1000000.0f; richTextBox1.AppendText("\n\n---------------------\n\n\n"); int substreamCount = 0; foreach (string key in greHash.Keys) { string[] ips = key.Split(','); richTextBox1.AppendText("GRE," + ips[0] + ", " + ips[1] + "," + ((Int64)greHash[key] * 8.0f / totalTime / 1000000.0f).ToString() + "," + ((Hashtable)greStreamHash[key]).Keys.Count.ToString() + "\n"); Hashtable streamHash = (Hashtable)greStreamHash[key]; foreach (string skey in streamHash.Keys) { substreamCount++; Int64 tbytes = (Int64)streamHash[skey]; float sbitrate = tbytes * 8.0f / totalTime / 1000000.0f; string[] newips = skey.Split(','); richTextBox1.AppendText("\t " + newips[0] + ", " + newips[1] + ", " + sbitrate.ToString() + "\n"); } } richTextBox1.AppendText("---------------------\n\n\n"); richTextBox1.AppendText("Capture: " + fname + "\n"); richTextBox1.AppendText("Total packet count is " + packetCount.ToString() + "\n"); richTextBox1.AppendText("Total MPLS Packet countis " + mplsPackets.ToString() + "\n"); richTextBox1.AppendText("Total MPLS Bytes is " + totalMPLSBytes.ToString() + "\n"); richTextBox1.AppendText("Unique GRE Streams: " + greHash.Keys.Count.ToString()); richTextBox1.AppendText("Total GRE substreams " + substreamCount.ToString() + "\n"); richTextBox1.AppendText("Average GRE Tunnel Bitrate = " + (grebitrate / greHash.Keys.Count).ToString() + "\n"); richTextBox1.AppendText("GRE Bitrate is " + (grebitrate).ToString() + " Mbits/sec \n"); richTextBox1.AppendText("Average GRE Substream bitrate = " + (grebitrate / substreamCount).ToString() + "\n"); richTextBox1.AppendText("MPLS Bitrate is " + (mplsbitrate).ToString() + " MBits/Sec\n"); richTextBox1.AppendText("Non GRE IP Bitrate is " + (ipbitrate).ToString() + " Mbits/sec\n"); richTextBox1.AppendText("Elapsed is " + totalTime.ToString() + "\n"); }
private void AnalyzeGRE(string filename, bool printSubstreams = false) { int streamcount = 0; if (filename !="") { txtFileName.Text = filename; greHash.Clear(); greStreamHash.Clear(); richTextBox1.Clear(); packetCount = 0; mplsPackets = 0; totalMPLSBytes = 0; richTextBox1.AppendText("Open file " +filename + "\n"); startTime = 0; lastPaketTime = 0; elapsedTime = 0; totalIPBytes = 0; totalGREBytes = 0; totalMPLSBytes = 0; OfflinePacketDevice interpreter = new OfflinePacketDevice(filename); using (PacketCommunicator communicator = interpreter.Open(250, PacketDeviceOpenAttributes.Promiscuous, 1000)) { communicator.ReceivePackets(0, DispatchHandler); } } else { richTextBox1.AppendText("No file"); return; } float totalTime = ((lastPaketTime - startTime) / 10000000.0f); float ipbitrate = totalIPBytes * 8.0f / totalTime / 1000000.0f; float grebitrate = totalGREBytes * 8.0f / totalTime / 1000000.0f; float mplsbitrate = totalMPLSBytes * 8 / totalTime / 1000000.0f; richTextBox1.AppendText("\n\n---------------------\n\n\n"); int substreamCount = 0; foreach (string key in greHash.Keys) { string[] ips = key.Split(','); richTextBox1.AppendText("GRE," + ips[0] + ", " + ips[1] + "," + ((Int64)greHash[key] * 8.0f / totalTime / 1000000.0f).ToString() + "," + ((Hashtable)greStreamHash[key]).Keys.Count.ToString() + "\n"); Hashtable streamHash = (Hashtable)greStreamHash[key]; streamcount += streamHash.Keys.Count; foreach (string skey in streamHash.Keys) { substreamCount++; Int64 tbytes = (Int64)streamHash[skey]; float sbitrate = tbytes * 8.0f / totalTime / 1000000.0f; string[] newips = skey.Split(','); if (printSubstreams) { richTextBox1.AppendText("\t " + newips[0] + ", " + newips[1] + ", " + sbitrate.ToString() + "\n"); } } } float averageStreamCount = 1.0f * streamcount / greHash.Keys.Count ; richTextBox1.AppendText("---------------------\n\n\n"); richTextBox1.AppendText("Capture: " + filename + "\n"); richTextBox1.AppendText("Total packet count: " + packetCount.ToString() + "\n"); richTextBox1.AppendText("Total MPLS Packet count: " + mplsPackets.ToString() + "\n\n"); richTextBox1.AppendText("Unique GRE discovered : " + greHash.Keys.Count.ToString() + "\n"); richTextBox1.AppendText("Total GRE substreams discovered: " + substreamCount.ToString() + "\n"); richTextBox1.AppendText("Average number of streams per GRE: " + averageStreamCount.ToString() + "\n\n"); richTextBox1.AppendText("Total GRE Bytes : " + totalGREBytes.ToString() + "\n"); richTextBox1.AppendText("Total MPLS Bytes is " + totalMPLSBytes.ToString() + "\n"); richTextBox1.AppendText("IP Only Bytes : " + totalIPBytes.ToString() + "\n"); richTextBox1.AppendText("Total Bytes from all protocols : " + totalBytes.ToString() + "\n\n"); richTextBox1.AppendText("GRE Bitrate is " + (grebitrate).ToString() + " Mbits/sec \n"); richTextBox1.AppendText("Average GRE Tunnel Bitrate = " + (grebitrate / greHash.Keys.Count).ToString() + "\n"); richTextBox1.AppendText("Average GRE Substream bitrate = " + (grebitrate / substreamCount).ToString() + " Mbps\n"); richTextBox1.AppendText("MPLS Bitrate is " + (mplsbitrate).ToString() + " MBits/Sec\n"); richTextBox1.AppendText("Non GRE IP Bitrate is " + (ipbitrate).ToString() + " Mbits/sec\n"); richTextBox1.AppendText("Length of capture in seconds: " + totalTime.ToString() + "\n"); }
public void Convert(CancellationToken cancellationToken = default(CancellationToken)) { FileInfo fi = new FileInfo(PcapFile); long fileSize = fi.Length; BinaryWriter idxWriter = new BinaryWriter(File.Open(GetDefaultIndexFile(PcapFile), FileMode.Create)); OfflinePacketDevice selectedDevice = new OfflinePacketDevice(PcapFile); PacketCommunicator communicator = selectedDevice.Open(65536, // portion of the packet to capture // 65536 guarantees that the whole packet will be captured on all the link layers PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode 1000); // read timeout using (BinaryWriter pointWriter = new BinaryWriter(File.Open(GetDefaultPointFile(PcapFile), FileMode.Create))) { Packet packet; bool isEof = false; VelodyneNmeaPacket lastNmea = null; long sumBytes = 0; long indexId = 0; while (!isEof) { if (cancellationToken.IsCancellationRequested) { idxWriter.Close(); cancellationToken.ThrowIfCancellationRequested(); } PacketCommunicatorReceiveResult result = communicator.ReceivePacket(out packet); switch (result) { case PacketCommunicatorReceiveResult.Timeout: case PacketCommunicatorReceiveResult.Ok: sumBytes += packet.Length; if (packet.Length == 554) { lastNmea = PacketInterpreter.ReadRecordNMEA(packet.Buffer); indexId++; } else { pointWriter.Write(packet.Timestamp.Ticks); pointWriter.Write(packet.Buffer); if (lastNmea != null) { int l = packet.Length - 6; // this is the end of the pack! double internal_time = BitConverter.ToUInt32(new byte[] { packet[l], packet[l + 1], packet[l + 2], packet[l + 3] }, 0) / 1000000.00; DateTime utcPacketTimestamp = packet.Timestamp.ToUniversalTime(); DateTime time = (new DateTime(utcPacketTimestamp.Year, utcPacketTimestamp.Month, utcPacketTimestamp.Day, utcPacketTimestamp.Hour, 0, 0)).AddSeconds(internal_time); idxWriter.Write(time.Ticks); idxWriter.Write(packet.Timestamp.Ticks); idxWriter.Write(pointWriter.BaseStream.Position); byte[] nmea_byte = Encoding.ASCII.GetBytes(lastNmea.NmeaString.PadRight(NMEA_LENGTH, ' ')); idxWriter.Write(nmea_byte); if (indexId % 100 == 0) { ProgressReportEventArgs args = new ProgressReportEventArgs((((double)sumBytes / (double)fileSize) * 100.0), sumBytes, utcPacketTimestamp); OnReportProgress(args); } lastNmea = null; } } break; case PacketCommunicatorReceiveResult.Eof: isEof = true; break; default: throw new InvalidOperationException("The result " + result + " should never be reached here"); } } } idxWriter.Close(); }
/// <summary> /// /// </summary> /// <param name="pcapPath"></param> /// <param name="outputPath"></param> /// <param name="maxSize"></param> public void Parse(string pcapPath, string outputPath, long maxSize) { this.cancelSource = new CancellationTokenSource(); Task task = Task.Factory.StartNew(() => { this.IsRunning = true; this.IsStopping = false; this.sessionParser.Start(); try { _outputPath = outputPath; _maxSize = maxSize; // Check for previous DB if (File.Exists(System.IO.Path.Combine(_outputPath, Global.DB_FILE)) == true) { OnMessage("Deleting database..."); string retDel = IO.DeleteFiles(_outputPath); if (retDel.Length > 0) { OnError("An error occurred whilst deleting the existing files: " + retDel); return; } } woanware.IO.WriteTextToFile("Start: " + DateTime.Now.ToString() + Environment.NewLine, System.IO.Path.Combine(_outputPath, "Log.txt"), true); OnMessage("Creating database..."); string ret = Db.CreateDatabase(_outputPath); if (ret.Length > 0) { OnError("Unable to create database: " + ret); return; } OnMessage("Database created..."); _packetCount = 0; _dictionary = new Dictionary<Connection, PacketReconstructor>(); OfflinePacketDevice selectedDevice = new OfflinePacketDevice(pcapPath); using (PacketCommunicator packetCommunicator = selectedDevice.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000)) { packetCommunicator.ReceivePackets(0, DispatcherHandler); } // Write any remaining sessions WriteOldSessions(null); _dictionary.Clear(); _dictionary = null; sessionParser.SetProcessed(); OnMessage("All sessions added to queue, now waiting for session parsing to complete..."); this.done = new AutoResetEvent(false); this.done.WaitOne(); woanware.IO.WriteTextToFile("End: " + DateTime.Now.ToString() + Environment.NewLine, System.IO.Path.Combine(_outputPath, "Log.txt"), true); woanware.IO.WriteTextToFile("Packets: " + _packetCount + Environment.NewLine, System.IO.Path.Combine(_outputPath, "Log.txt"), true); woanware.IO.WriteTextToFile("TCP Sessions: " + this.sessionParser.TotalSessions + Environment.NewLine, System.IO.Path.Combine(_outputPath, "Log.txt"), true); OnComplete(); } catch (Exception ex) { OnError("An error occurred whilst parsing: " + ex.Message); } finally { IsRunning = false; } }, cancelSource.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default); }
private void openToolStripMenuItem_Click(object sender, EventArgs e) { if (openFileDialog1.ShowDialog() == DialogResult.OK) { packetCount = 0; startTime = 0; listView1.Items.Clear(); Debug.WriteLine("Selected file: " + openFileDialog1.FileName); OfflinePacketDevice interpreter = new OfflinePacketDevice(openFileDialog1.FileName); using (PacketCommunicator communicator = interpreter.Open(250, PacketDeviceOpenAttributes.Promiscuous, 1000)) { communicator.ReceivePackets(0, DispatchHandler); } } else { Debug.WriteLine("No file"); } }
/// <summary> /// Start an off-line capture /// </summary> /// <param name="file">The dump file name to capture</param> /// <param name="callback">Callback to handle packets</param> /// <param name="IsBadDumpFile">Flag indicates whether the dump file is invalid</param> public static void StartOfflineCapture(string file, HandlePacket callback, ref bool IsBadDumpFile) { PacketCommunicator pc = communicator; try { // Create the off-line device OfflinePacketDevice selectedDevice = new OfflinePacketDevice(file); communicator = selectedDevice.Open(65536, // portion of the packet to capture // 65536 guarantees that the whole packet will be captured on all the link layers PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode 1000); // read timeout // Compile the filter using (BerkeleyPacketFilter filter = communicator.CreateFilter(SnifferConfig.Filter.FilterString)) { communicator.SetFilter(filter); } // Read and dispatch packets until EOF is reached communicator.ReceivePackets(0, callback); } catch (Exception) { IsBadDumpFile = true; } finally { if (pc != null) communicator = pc; } }
public bool ParseCaptureFile(string fileNameAndPath, string fileName, bool includeParsedFileLog) { bool result = false; // Create an offline device for the capture file OfflinePacketDevice opd = new OfflinePacketDevice(fileNameAndPath); // Create a container to hold the captured packets BindingList<Packet> packets = new BindingList<Packet>(); // Open the capture file (snapshot length, attributes, read timeout) using (PacketCommunicator com = opd.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000)) { // Retrieve the packets Packet packet; string pktResult = string.Empty; do { PacketCommunicatorReceiveResult rec = com.ReceivePacket(out packet); pktResult = rec.ToString(); switch(rec) { case PacketCommunicatorReceiveResult.Timeout: // Timeout elapsed continue; case PacketCommunicatorReceiveResult.Ok: packets.Add(packet); break; case PacketCommunicatorReceiveResult.Eof: break; default: throw new InvalidOperationException("Unknown error occurred while reading packet: " + result); } } while (pktResult != "Eof"); } if(packets.Count > 0) { // We successfully parsed the capture file // Note: in future version we may need to compare the number of rows in the file with the number of parsed packets obtained result = true; } // Write packets out to a file if (result && includeParsedFileLog) { int pktno = 0; using (StreamWriter sw = new StreamWriter(ParsedFilesDir + "\\ParsePacketTest_" + DateTime.Now.Ticks.ToString() + ".txt")) { foreach (Packet pkt in packets) { StringBuilder sb = new StringBuilder(); sb.AppendFormat("{0}|{1}|{2}", fileName, pktno++, Convert.ToDateTime(pkt.Timestamp).TimeOfDay); sw.WriteLine(sb.ToString()); } } } // Check if packets are marked (i.e., flooder was running during packet capture 'd', or unmarked, 'u') int marked = fileName.Substring(fileName.Length - 6, 1) == "u" ? 0 : 1; int captureBatchId = -1; // Write a CaptureBatch record to the database for this file if(result) { try { DataImport di = new DataImport(DbConnectionString); captureBatchId = di.CreateCaptureBatch(fileName, marked == 1? true : false); result = captureBatchId > 0 ? true : false; } catch (Exception ex) { throw new Exception("Error creating CaptureBatch record in database for file [" + fileName + "]: " + ex.Message); } } // Write packets to a DataTable and import them into the database if (result) { DataSet packetDs = new DataSet(); DataTable packetTable = new DataTable(); PacketDataSet.PacketDataSet pds = new PacketDataSet.PacketDataSet(); try { int pktno = 0; packetTable = pds.CreatePacketDataTable(); { foreach (Packet pkt in packets) { DataRow dr = packetTable.NewRow(); dr["CaptureBatchId"] = captureBatchId; dr["PacketNumber"] = pktno++; dr["TimeStamp"] = Convert.ToDateTime(pkt.Timestamp).TimeOfDay.ToString(); dr["Marked"] = marked; packetTable.Rows.Add(dr); } } } catch (Exception ex) { throw new Exception("Error adding packet data row to DataTable: " + ex.Message); } try { // Import into the database COWE.DataLayer.DataImport di = new DataImport(DbConnectionString); bool success = di.LoadPacketData(packetTable); } catch (Exception ex) { throw new Exception("Error importing packet data into database: " + ex.Message); } } return result; }