private void mCaptureTimer_Tick(object pSender, EventArgs pArgs) { if (mCaptureDevice == null) return; if (mClosing) { mCaptureDevice.Close(); mCaptureDevice = null; return; } Packet packet = null; while ((packet = mCaptureDevice.GetNextPacket()) != null) { TCPPacket tcpPacket = packet as TCPPacket; SessionForm session = null; if (tcpPacket.Syn && !tcpPacket.Ack) { session = Array.Find(MdiChildren, f => (f as SessionForm).MatchTCPPacket(tcpPacket)) as SessionForm; if (session == null) { session = NewSession(); } } else session = Array.Find(MdiChildren, f => (f as SessionForm).MatchTCPPacket(tcpPacket)) as SessionForm; if (session != null) session.BufferTCPPacket(tcpPacket); } }
public ChooseDeviceForm(PcapDevice device) { InitializeComponent(); nics = NetworkInterface.GetAllNetworkInterfaces(); FillComboBoxDevices(); comboBoxDevices.SelectedIndexChanged += new EventHandler(comboBoxDevices_SelectedIndexChanged); if (comboBoxDevices.Items.Count > 0) { comboBoxDevices.SelectedItem = device; if (device != null) { buttonStart.Enabled = !device.Started; buttonStop.Enabled = device.Started; } else { buttonStart.Enabled = false; buttonStop.Enabled = false; } } else { buttonStart.Enabled = false; buttonStop.Enabled = false; } }
// Disposer public void Dispose() { if(trackdevice != null) { // Stop capturing packets try { trackdevice.StopCapture(); } catch(Exception) { }; try { trackdevice.Close(); } catch(Exception) { }; trackdevice = null; } }
private string GetStatistics(PcapDevice device) { StringBuilder statBuilder = new StringBuilder(); statBuilder.Append("Pcap Statistics\n"); statBuilder.Append("=====================================\n"); statBuilder.AppendFormat(" Received Packets .............. : {0}\n", device.Statistics().ReceivedPackets); statBuilder.AppendFormat(" Dropped Packets ............... : {0}\n", device.Statistics().DroppedPackets); statBuilder.AppendFormat(" Interface Dropped Packets ..... : {0}\n", device.Statistics().InterfaceDroppedPackets); return statBuilder.ToString(); }
/// <summary> /// Send a queue of raw packets to the network. /// </summary> /// <param name="device">The PcapDevice on which to send the queue</param> /// <param name="synchronize">determines if the send operation must be synchronized: /// if it is non-zero, the packets are sent respecting the timestamps, /// otherwise they are sent as fast as possible /// <returns></returns> public int Transmit(PcapDevice device, bool synchronize) { if (!device.Opened) { throw new PcapException("Can't transmit queue, the pcap device is closed."); } if (m_queue == IntPtr.Zero) { throw new PcapException("Can't transmit queue, this queue is disposed"); } int sync = synchronize ? 1 : 0; return(SafeNativeMethods.pcap_sendqueue_transmit(device.PcapHandle, m_queue, sync)); }
// This starts the capturing public void Start() { // DISABLED return; List<PcapDevice> devices = Pcap.GetAllDevices(); if(devices.Count < 1) { General.Fail("No network devices connected."); return; } // Find the device we want to track traffic on foreach(PcapDevice dev in devices) { // Just pick any device that has an address if(dev.Addresses.Count > 0) trackdevice = dev; } string addrstr = ""; for(int i = 0; i < trackdevice.Addresses.Count; i++) { if(trackdevice.Addresses[i].Addr.type != SharpPcap.Containers.Sockaddr.Type.HARDWARE) { if(addrstr.Length > 0) addrstr += ", "; addrstr += "'" + trackdevice.Addresses[i].Addr.ipAddress + "'"; } } General.WriteLogLine("Tracking network on device '" + trackdevice.Description.Trim() + "' with address " + addrstr); // Start capturing packets trackdevice.Open(true, 1000); trackdevice.OnPacketArrival += PacketHandler; trackdevice.StartCapture(); }
/// <summary> /// Send a queue of raw packets to the network. /// </summary> /// <param name="device">The PcapDevice on which to send the queue</param> /// <param name="synchronize">determines if the send operation must be synchronized: /// if it is non-zero, the packets are sent respecting the timestamps, /// otherwise they are sent as fast as possible /// <returns></returns> public int Transmit( PcapDevice device, bool synchronize) { if(!device.Opened) throw new PcapException("Can't transmit queue, the pcap device is closed."); if(m_queue==IntPtr.Zero) { throw new PcapException("Can't transmit queue, this queue is disposed"); } int sync = synchronize ? 1 : 0; return SafeNativeMethods.pcap_sendqueue_transmit(device.PcapHandle, m_queue, sync); }
private void StartScan() { scannerType = (ScannerType)comboBoxScannerType.SelectedValue; scanMethod = (ScanMethod)comboBoxScanMethod.SelectedValue; delay = Int32.Parse(textBoxDelay.Text); timeout = Int32.Parse(textBoxTimeout.Text); string[] hosts = textBoxHost.Text.Trim().Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); hostEntries = new IPHostEntry[hosts.Length]; for (int i = 0; i < hosts.Length; i++) { hostEntries[i] = Dns.GetHostEntry(hosts[i]); } fromPort = Int32.Parse(textBoxFromPort.Text); if (textBoxToPort.Visible) { toPort = Int32.Parse(textBoxToPort.Text); } device = chooseDeviceUserControl.Device; // Matching selected interface with .NET's facilities in order to get gateway's ip address // that is a property of the network interface of interest. NetworkInterface adapter = GetMatchingNetworkInterface(device.Interface, nics); if (adapter == null) { throw new Exception("Network interface not found."); } if (scanMethod == ScanMethod.SynScan) { if (device.Opened) { MessageBox.Show("The sniffing process must be stopped in order to perform SYN Scan.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } IPInterfaceProperties properties = adapter.GetIPProperties(); GatewayIPAddressInformationCollection gateways = properties.GatewayAddresses; if (gateways.Count > 0) { gateway = gateways[0].Address; } else { throw new Exception("No gateway address found."); } } textBoxScanResult.Clear(); buttonStartScan.Enabled = false; buttonSaveLog.Enabled = false; backgroundWorkerScan.RunWorkerAsync(); }
public SynConnectCall(int timeout, PcapDevice device, IPAddress gatewayAddress) { this.timeout = timeout; this.device = device; this.gatewayAddress = gatewayAddress; }
/// <summary> /// Retrieve pcap statistics from the adapter /// </summary> /// <param name="pcap_t"> /// pcap_t* for the adapter /// A <see cref="IntPtr"/> /// </param> internal PcapStatistics(IntPtr pcap_t) { IntPtr stat; if (Environment.OSVersion.Platform == PlatformID.Unix) { // allocate memory for the struct stat = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(PcapUnmanagedStructures.pcap_stat_unix))); } else { // allocate memory for the struct stat = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(PcapUnmanagedStructures.pcap_stat_windows))); } // retrieve the stats PcapUnmanagedStructures.PcapStatReturnValue result = (PcapUnmanagedStructures.PcapStatReturnValue)SafeNativeMethods.pcap_stats(pcap_t, stat); // process the return value switch (result) { case PcapUnmanagedStructures.PcapStatReturnValue.Error: // retrieve the error information string error = PcapDevice.GetLastError(pcap_t); // free the stats memory so we don't leak before we throw Marshal.FreeHGlobal(stat); throw new PcapStatisticsException(error); case PcapUnmanagedStructures.PcapStatReturnValue.Success: // nothing to do upon success break; } // marshal the unmanaged memory into an object of the proper type if (Environment.OSVersion.Platform == PlatformID.Unix) { PcapUnmanagedStructures.pcap_stat_unix managedStat = (PcapUnmanagedStructures.pcap_stat_unix)Marshal.PtrToStructure(stat, typeof(PcapUnmanagedStructures.pcap_stat_unix)); // copy the values this.ReceivedPackets = (int)managedStat.ps_recv; this.DroppedPackets = (int)managedStat.ps_drop; // this.InterfaceDroppedPackets = (int)managedStat.ps_ifdrop; } else { PcapUnmanagedStructures.pcap_stat_windows managedStat = (PcapUnmanagedStructures.pcap_stat_windows)Marshal.PtrToStructure(stat, typeof(PcapUnmanagedStructures.pcap_stat_windows)); // copy the values this.ReceivedPackets = (int)managedStat.ps_recv; this.DroppedPackets = (int)managedStat.ps_drop; // this.InterfaceDroppedPackets = (int)managedStat.ps_ifdrop; } // NOTE: Not supported on unix or winpcap, no need to // put a bogus value in this field this.InterfaceDroppedPackets = 0; // free the stats Marshal.FreeHGlobal(stat); }
public PcapStatisticsModeEventArgs(Packets.Packet packet, PcapDevice device) : base(packet, device) { }
public PcapCaptureEventArgs(Packets.Packet packet, PcapDevice device) { this.packet = packet; this.device = device; }
private void mFileCaptureMenu_Click(object pSender, EventArgs pArgs) { if (mCaptureDevice != null) { mCaptureDevice.Close(); mCaptureDevice = null; return; } SetupForm frmSetup = new SetupForm(); if (frmSetup.ShowDialog(this) != DialogResult.OK) return; foreach (PcapDevice device in new PcapDeviceList()) { if (device.Interface.FriendlyName == Config.Instance.Interface) { mCaptureDevice = device; break; } } mCaptureDevice.Open(true, 1); mCaptureDevice.SetFilter(string.Format("tcp portrange {0}-{1}", Config.Instance.LowPort, Config.Instance.HighPort)); }
private void button1_Click(object sender, EventArgs e) { textBox4.Clear(); button1.Enabled = false; try { _scannerType = comboBox1.SelectedItem.ToString(); _scanMethod = comboBox2.SelectedItem.ToString(); portFrom = Convert.ToInt32(textBox1.Text); if (textBox2.Enabled) portTo = Convert.ToInt32(textBox2.Text); dev = (PcapDevice)comboBox3.SelectedItem; //Matching selected interface with .NET's facilities in order to get gateway's ip address //that is a property of the network interface of interest. foreach (NetworkInterface f in NetworkInterface.GetAllNetworkInterfaces()) { if (dev.Interface.Name.Contains(f.Id)) { gateway = f.GetIPProperties().GatewayAddresses[0].Address; break; } } backgroundWorker1.RunWorkerAsync(); } catch (Exception ex) { textBox4.Text = "You have to insert all appropriate parameters.\n"; textBox4.Text = ex.Message; button1.Enabled = true; } }
public SynConnectCall(int timeout, PcapDevice dev, IPAddress addr) { _timeout = timeout; _dev = dev; _gatewayAddr = addr; }
private void MainForm_Load(object pSender, EventArgs pArgs) { if (new SetupForm().ShowDialog(this) != DialogResult.OK) { Close(); return; } foreach (PcapDevice device in new PcapDeviceList()) { if (device.Interface.FriendlyName == Config.Instance.Interface) { mDevice = device; break; } } mDevice.Open(true, 1); mDevice.SetFilter(string.Format("tcp portrange {0}-{1}", Config.Instance.LowPort, Config.Instance.HighPort)); mTimer.Enabled = true; mSearchForm.Show(mDockPanel); mDataForm.Show(mDockPanel); mStructureForm.Show(mDockPanel); mPropertyForm.Show(mDockPanel); DockPane rightPane1 = new DockPane(mStructureForm, DockState.DockRight, true); DockPane rightPane2 = new DockPane(mPropertyForm, DockState.DockRight, true); rightPane1.Show(); rightPane2.Show(); }
private void devicesToolStripMenuItem_Click(object sender, EventArgs e) { using (ChooseDeviceForm chooseDeviceForm = new ChooseDeviceForm(device)) { chooseDeviceForm.ButtonStopPressed += new EventHandler(chooseDeviceForm_ButtonStopPressed); if (chooseDeviceForm.ShowDialog() == DialogResult.OK) { device = chooseDeviceForm.Device; StartCapture(); } } }
private string GetNonAdapterDeviceInfo(PcapDevice device) { if (device == null) { return String.Empty; } StringBuilder infoBuilder = new StringBuilder(); infoBuilder.Append(device.Interface.Description + "\n"); infoBuilder.Append("=================================================\n"); infoBuilder.AppendFormat(" Name ....................... : {0}\n", device.Interface.Name); infoBuilder.AppendFormat(" Friendly name .............. : {0}\n", device.Interface.FriendlyName); infoBuilder.Append(" Addresses .................. :\n"); infoBuilder.Append(GetPcapAddresses(device.Interface.Addresses)); infoBuilder.AppendFormat(" Flags ...................... : {0}\n", device.Interface.Flags); return infoBuilder.ToString(); }
public SummaryForm(PcapDevice device) { InitializeComponent(); richTextBoxSummary.Text = GetStatistics(device); }