Exemplo n.º 1
0
 public MainForm(List <LibPcapLiveDevice> interfaces, int selectedIndex)
 {
     InitializeComponent();
     interfaceList    = interfaces;
     selectedIntIndex = selectedIndex;
     wifi_device      = interfaceList[selectedIntIndex];
 }
Exemplo n.º 2
0
        private static LibPcapLiveDevice GetDevice(IPAddress address)
        {
            var addrBytes            = address.GetAddressBytes();
            var devices              = LibPcapLiveDeviceList.Instance;
            LibPcapLiveDevice device = null;

            foreach (var dev in devices)
            {
                foreach (var addr in dev.Addresses)
                {
                    if (addr.Addr.ipAddress != null)
                    {
                        if (addr.Addr.ipAddress.GetAddressBytes().SequenceEqual(addrBytes))
                        {
                            device = dev;
                            break;
                        }
                    }
                }

                if (device != null)
                {
                    break;
                }
            }

            return(device);
        }
Exemplo n.º 3
0
        public void SendPacketFromDataBox(LibPcapLiveDevice Device, byte [] Packt, bool?PeriodEn, int Period)
        {
            Device.Open();
            SendingThreadEnable = true;
            Thread td = new Thread(() =>
            {
                while (true)
                {
                    if (SendingThreadEnable == false)
                    {
                        break;
                    }
                    try
                    {
                        Device.SendPacket(Packt);
                    }
                    catch
                    {
                        break;
                    }
                    if (PeriodEn == true)
                    {
                        Thread.Sleep(Period);
                    }
                    else
                    {
                        break;
                    }
                }
            });

            td.Start();
        }
Exemplo n.º 4
0
        public ArpTool(LibPcapLiveDevice device)
        {
            _device = device;

            foreach (var address in _device.Addresses)
            {
                if (address.Addr.type == Sockaddr.AddressTypes.AF_INET_AF_INET6)
                {
                    if (address.Addr.ipAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                    {
                        LocalIP = address.Addr.ipAddress;
                        break;
                    }
                }
            }

            foreach (var address in device.Addresses)
            {
                if (address.Addr.type == SharpPcap.LibPcap.Sockaddr.AddressTypes.HARDWARE)
                {
                    LocalMAC = address.Addr.hardwareAddress;
                }
            }

            GetwayIP  = _device.Interface.GatewayAddress;
            GetwayMAC = Resolve(GetwayIP);
        }
        public static PhysicalAddress ResolveMac(LibPcapLiveDevice device, IPAddress Instance)
        {
            ARP Resolver = new ARP(device);

            Resolver.Timeout = new TimeSpan(0, 0, 3);
            return(Resolver.Resolve(Instance, getLocaIP(), GetMacAddress()));
        }
Exemplo n.º 6
0
 public CbxObjectItem(string text, int index, LibPcapLiveDevice dev, PcapAddress ipv4)
 {
     this.text  = text;
     this.index = index;
     this.dev   = dev;
     this.ipv4  = ipv4;
 }
Exemplo n.º 7
0
        public string scanHost(string host)
        {
            // Parse target IP addr

            LibPcapLiveDevice device   = getDevice();
            IPAddress         targetIP = null;

            bool ok = IPAddress.TryParse(host, out targetIP);

            if (!ok)
            {
                Console.WriteLine("Invalid IP.");
                return("fail");
            }

            // Create a new ARP resolver
            ARP arp = new ARP(device);

            arp.Timeout = new System.TimeSpan(scanDelay); // 100ms

            // Enviar ARP
            var resolvedMacAddress = arp.Resolve(targetIP);

            if (resolvedMacAddress == null)
            {
                return("fail");
            }
            else
            {
                string fmac = formatMac(resolvedMacAddress);
                Console.WriteLine(targetIP + " is at: " + fmac);

                return(fmac);
            }
        }
Exemplo n.º 8
0
        private LibPcapLiveDevice loadCaptureDevice(String capture_device_name)
        {
            LibPcapLiveDevice pdev = null;

            if (System.Environment.OSVersion.Platform == PlatformID.Win32NT)
            {
                foreach (WinPcapDevice dev in capture_devices_win)
                {
                    if (dev.Name == capture_device_name)
                    {
                        pdev = dev;
                    }
                }
            }
            else
            {
                foreach (LibPcapLiveDevice dev in capture_devices)
                {
                    if (dev.Name == capture_device_name)
                    {
                        pdev = dev;
                    }
                }
            }
            return(pdev);
        }
Exemplo n.º 9
0
        private void buttonStartStop_Click(object sender, EventArgs e)
        {
            if (buttonStartStop.Text.Equals("Start"))
            {
                if (mInterfaces.SelectedIndex > -1 && mInterfaces.SelectedIndex < interfaceList.Count)
                {
                    buttonStartStop.Text = "Stop";
                    listPackets.Items.Clear();
                    capturedPackets_list.Clear();
                    packetNumber = 1;

                    device = interfaceList[mInterfaces.SelectedIndex];
                    device.OnPacketArrival += new SharpPcap.PacketArrivalEventHandler(Device_OnPacketArrival);
                    sniffing = new Thread(new ThreadStart(sniffing_Proccess));
                    sniffing.Start();
                }
            }
            else
            {
                buttonStartStop.Text = "Start";
                sniffing.Abort();
                device.StopCapture();
                device.Close();
            }
        }
        /// <summary>
        /// Constructs a new ARP Resolver
        /// </summary>
        /// <param name="device">The network device on which this resolver sends its ARP packets</param>
        public ArpForIpConflict(LibPcapLiveDevice device)
        {
            _device = device;
            if (_device.Addresses.Count > 0)
            {
                // attempt to find an ipv4 address.
                // ARP is ipv4, NDP is used for ipv6
                foreach (var address in _device.Addresses)
                {
                    if (address.Addr.type == Sockaddr.AddressTypes.AF_INET_AF_INET6)
                    {
                        // make sure the address is ipv4
                        if (address.Addr.ipAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                        {
                            LocalIP = address.Addr.ipAddress;
                            break; // break out of the foreach
                        }
                    }
                }

                // if we can't find either an ipv6 or an ipv4 address use the localhost address
                if (LocalIP == null)
                {
                    LocalIP = IPAddress.Parse("127.0.0.1");
                }
            }

            foreach (var address in _device.Addresses)
            {
                if (address.Addr.type == Sockaddr.AddressTypes.HARDWARE)
                {
                    LocalMAC = address.Addr.hardwareAddress;
                }
            }
        }
Exemplo n.º 11
0
        private void SetDevice(LibPcapLiveDevice device)
        {
            var ip_info = NetUtils.GetIPAddressInfo(device);

            textBox_ip_debut.Text = NetUtils.GetNextIP(ip_info.IPNetwork).ToString();
            textBox_ip_fin.Text   = NetUtils.GetPreviousIp(ip_info.IPBroadcast).ToString();

            scanner.Device = device;

            foreach (TabPage tab in tabControl.TabPages)
            {
                var uc = tab.Controls[0] as ControlTowerUserControl;
                if (uc != null)
                {
                    uc.Device = device;
                }
            }

            var macAddress = NetUtils.GetPhysicalAddress(device);
            var ipAddress  = NetUtils.GetIPAddressInfo(device);

            HostManager.Instance.AddHost(this, new HostEventArgs()
            {
                Host = new Host()
                {
                    IpAddress  = ipAddress.IPAddress,
                    MacAddress = macAddress,
                    Name       = $"<This computer>"
                }
            });
        }
 private void cobInterfaces_SelectedIndexChanged(object sender, EventArgs e)
 {
     if (Stopped)
     {
         wifi_device = Interfaces[cobInterfaces.SelectedIndex];
     }
 }
Exemplo n.º 13
0
        public event EventHandler <EventArgs> ScanStopedEvent;     //扫描结束事件

        /// <summary>
        /// Constructs a new ARP Resolver 构造一个新的ARP解析器
        /// </summary>
        /// <param name="device">The network device on which this resolver sends its ARP packets 该解析器发送ARP数据包的网络设备 </param>
        public ARPTool(LibPcapLiveDevice device)
        {
            _device = device;

            foreach (var address in _device.Addresses)
            {
                if (address.Addr.type == Sockaddr.AddressTypes.AF_INET_AF_INET6)
                {
                    // make sure the address is ipv4 确保地址是IPv4
                    if (address.Addr.ipAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                    {
                        LocalIP = address.Addr.ipAddress;
                        break; // break out of the foreach 跳出循环
                    }
                }
            }

            foreach (var address in device.Addresses)
            {
                if (address.Addr.type == Sockaddr.AddressTypes.HARDWARE)
                {
                    LocalMAC = address.Addr.hardwareAddress; // 本机MAC
                }
            }



            GetwayIP  = _device.Interface.GatewayAddress; // 网关IP
            GetwayMAC = Resolve(GetwayIP);                // 网关MAC
        }
Exemplo n.º 14
0
        private CaptureDevice()
        {
            var networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
            var networkInterface  = networkInterfaces
                                    .Where(x => x.OperationalStatus == OperationalStatus.Up)
                                    .Where(x => x.GetIPProperties() != null)
                                    .First(x => x.GetIPProperties().GatewayAddresses.Any(y => y.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork));

            this.IpAddress = networkInterface.GetIPProperties().UnicastAddresses.Where(x => x.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork).Select(x => x.Address).First();
            var gatewayAddress = networkInterface.GetIPProperties().GatewayAddresses.First();

            try
            {
                this.device = LibPcapLiveDeviceList.Instance.First(x => x.Interface.Name.Contains(networkInterface.Id));
            }
            catch (Exception)
            {
                MessageBox.Show($"{nameof(PentestBro)} will not work properly, please install WinPCAP correctly.");
                return;
            }

            this.device.Open(DeviceMode.Normal, 20);

            this.DefaultGatewayMacAddress = this.GetMacAddress(gatewayAddress.Address);

            for (var i = 0; i < 12; i++)
            {
                this.MacAddress += device.MacAddress.ToString()[i];

                if (i == 1 || i == 3 || i == 5 || i == 7 || i == 9)
                {
                    this.MacAddress += ":";
                }
            }
        }
Exemplo n.º 15
0
        /// <summary>
        /// 初始化获取网卡列表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_Load(object sender, EventArgs e)
        {
            richTextBox1.LoadFile("Law.rtf");

            try
            {
                devicesList = LibPcapLiveDeviceList.Instance;
                //显示网卡详细信息
                //for (int i = 0; i < devicesList.Count; i++)
                //{
                //    MessageBox.Show(devicesList[i].ToString());
                //}

                if (devicesList.Count < 1)
                {
                    throw new Exception("没有发现本机上的网络设备");
                }

                device = devicesList[0];

                combDevice.DataSource = devicesList;
            }
            catch
            {
                MessageBox.Show("你没有安装WinPcap,请在打开的网站中下载安装WinPacp后,重启本软件");
                System.Diagnostics.Process.Start("https://www.winpcap.org/");
            }//获取本机所有网卡
        }
Exemplo n.º 16
0
 /// <summary>
 /// 获取网卡信息并将结果返回到UI,若选择的是虚拟网卡返回空值
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void combDevice_SelectedIndexChanged(object sender, EventArgs e)
 {
     // 获取相应的设备网关MAC,IP,本机MAC,IP
     device = devicesList[(sender as ComboBox).SelectedIndex];
     if (device.Interface.FriendlyName.IndexOf("Adapter") == -1 && device.Interface.Description.IndexOf("LoopBack") == -1)
     {
         arpTool = new ARPTool(device);
         arpTool.ScanStopedEvent   += arpTool_ScanStopedEvent;
         arpTool.ResolvedEvent     += arpTool_ResolvedEvent;
         arpTool.ResolvedTimeEvent += arpTool_ResolvedTimeEvent;
         txtLocalIP.Text            = arpTool.LocalIP.ToString();
         txtLocalMAC.Text           = Regex.Replace(arpTool.LocalMAC.ToString(), @"(\w{2})", "$1-").Trim('-');
         txtGatewayIP.Text          = arpTool.GetwayIP.ToString();
         txtGatewayMAC.Text         = Regex.Replace(arpTool.GetwayMAC.ToString(), @"(\w{2})", "$1-").Trim('-');
         txtSenderIP.Text           = arpTool.GetwayIP.ToString();
         txtSenderMAC.Text          = Regex.Replace(GetRandomPhysicalAddress().ToString(), @"(\w{2})", "$1-").Trim('-');
     }
     else
     {
         txtLocalIP.Text    = "";
         txtLocalMAC.Text   = "";
         txtGatewayIP.Text  = "";
         txtGatewayMAC.Text = "";
         txtSenderIP.Text   = "";
         txtSenderMAC.Text  = "";
     }
 }
Exemplo n.º 17
0
        /// <summary>
        /// Starts the target manager thread.
        /// </summary>
        public void Start()
        {
            Messages.Trace("starting communications manager");

            // get the packet capture device
            CaptureDeviceList devices = CaptureDeviceList.Instance;

            capDevice = devices[Program.interfaceToUse];
            Messages.Trace("using [" + capDevice.Description + "] for network capture");

            capDevice.OnPacketArrival += capDevice_OnPacketArrival;

            if (capDevice is WinPcapDevice)
            {
                WinPcapDevice winPcap = capDevice as WinPcapDevice;
                winPcap.Open(OpenFlags.Promiscuous | OpenFlags.NoCaptureLocal | OpenFlags.MaxResponsiveness, readTimeoutMilliseconds);
            }
            else if (capDevice is LibPcapLiveDevice)
            {
                LibPcapLiveDevice livePcapDevice = capDevice as LibPcapLiveDevice;
                livePcapDevice.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);
            }
            else
            {
                throw new InvalidOperationException("unknown device type of " + capDevice.GetType().ToString());
            }

            capDevice.StartCapture();

            // start loop
            runThread = true;
            commMgrThread.Start();
        }
Exemplo n.º 18
0
        private void lbxLibPcapLiveDeviceListI_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            gbxDevInfoI.Visibility = Visibility.Visible;
            LibPcapLiveDevice dev = lbxLibPcapLiveDeviceListI.SelectedItem as LibPcapLiveDevice;

            gbxDevInfo.DataContext   = dev;
            lbxAdressesI.ItemsSource = dev.Addresses;
        }
Exemplo n.º 19
0
        public NetworkInterface(IEventAggregator eventAggregator, LibPcapLiveDevice device, string name)
        {
            _eventAggregator = eventAggregator;
            _stopwatch       = new Stopwatch();

            Device = device;
            Name   = name;
        }
Exemplo n.º 20
0
        public void TestFilters()
        {
            // test a known failing filter
            Assert.IsFalse(LibPcapLiveDevice.CheckFilter("some bogus filter", out string errorString));

            // test a known working filter
            Assert.IsTrue(LibPcapLiveDevice.CheckFilter("port 23", out errorString));
        }
Exemplo n.º 21
0
        private static LibPcapLiveDevice getFirstDevice()
        {
            var devices = getDeviceList();

            LibPcapLiveDevice device = devices[0];

            return(device);
        }
Exemplo n.º 22
0
 public MainForm(List <LibPcapLiveDevice> interfaces, int selectedIndex)
 {
     InitializeComponent();
     this.interfaceList = interfaces;
     selectedIntIndex   = selectedIndex;
     // Extract a device from the list
     wifi_device = interfaceList[selectedIntIndex];
 }
Exemplo n.º 23
0
        public override void SessionStarting()
        {
            if (_deviceName == null)
            {
                throw new PeachException("Error, PcapMonitor requires a device name.");
            }

            // Retrieve all capture devices
            // Don't use the singlton interface so we can support multiple
            // captures on the same device with different filters
            var devices = _GetDeviceList();

            if (devices.Count == 0)
            {
                throw new PeachException("No pcap devices found. Ensure appropriate permissions for using libpcap.");
            }

            // differentiate based upon types
            foreach (var item in devices)
            {
                var dev = item as LibPcapLiveDevice;
                System.Diagnostics.Debug.Assert(dev != null);
                if (dev.Interface.FriendlyName == _deviceName)
                {
                    _device = dev;
                    break;
                }
            }

            if (_device == null)
            {
                Console.WriteLine("Found the following pcap devices: ");
                foreach (var item in devices)
                {
                    var dev = item as LibPcapLiveDevice;
                    System.Diagnostics.Debug.Assert(dev != null);
                    if (dev.Interface.FriendlyName != null && dev.Interface.FriendlyName.Length > 0)
                    {
                        Console.WriteLine(" " + dev.Interface.FriendlyName);
                    }
                }
                throw new PeachException("Error, PcapMonitor was unable to locate device '" + _deviceName + "'.");
            }

            _device.OnPacketArrival += new PacketArrivalEventHandler(_OnPacketArrival);
            _device.Open();

            try
            {
                _device.Filter = _filter;
            }
            catch (PcapException ex)
            {
                throw new PeachException("Error, PcapMonitor was unable to set the filter '" + _filter + "'.", ex);
            }

            _device.StartCapture();
        }
Exemplo n.º 24
0
        public void ReceivePacketsWithStartCapture()
        {
            // We can't use the same device for async capturing and sending
            var device = GetPcapDevice();

            using var receiver = new LibPcapLiveDevice(device.Interface);
            using var sender   = new LibPcapLiveDevice(receiver.Interface);
            CheckExchange(sender, receiver);
        }
Exemplo n.º 25
0
        public static void Main(string[] args)
        {
            string netz = null;

            if (args.Length < 1)
            {
                Console.WriteLine("Subnetz nicht angegeben --> automatische Auswahl");
                netz = GetNetz();
                if (netz == null)
                {
                    Console.WriteLine("keine passendes Netzwerk gefunden"); return;
                }
            }
            else
            {
                netz = args[0];
            }
            if (!netz.EndsWith("."))
            {
                netz += ".";
            }
            string    testIp = netz + "1";
            IPAddress ip;

            if (!IPAddress.TryParse(testIp, out ip))
            {
                Console.WriteLine("kein gültiges Subnetz angegeben " + netz); return;
            }
            device = GetDevice(netz);
            if (device == null)
            {
                Console.WriteLine("keine Netzwerkkarte im Subnetz " + netz); return;
            }

            bool end = false;

            while (!end)
            {
                //StartPcapSniffer();
                ActivePollMacs(netz);

                // 30s warten
                Console.WriteLine("q zum beenden");
                for (int i = 0; i < 30; i++)
                {
                    System.Threading.Thread.Sleep(1000);
                    if (Console.KeyAvailable)
                    {
                        var k = Console.ReadKey();
                        if (k.KeyChar.Equals('q'))
                        {
                            return;
                        }
                    }
                }
            }
        }
Exemplo n.º 26
0
        public void ReceivePacketsWithStartCapture()
        {
            const int PacketsCount = 10;
            var       packets      = new List <RawCapture>();
            var       statuses     = new List <CaptureStoppedEventStatus>();

            void Receiver_OnPacketArrival(object s, CaptureEventArgs e)
            {
                packets.Add(e.Packet);
            }

            void Receiver_OnCaptureStopped(object s, CaptureStoppedEventStatus status)
            {
                statuses.Add(status);
            }

            // We can't use the same device for async capturing and sending
            var device   = GetPcapDevice();
            var receiver = new LibPcapLiveDevice(device.Interface);
            var sender   = new LibPcapLiveDevice(receiver.Interface);

            try
            {
                // Configure sender
                sender.Open();

                // Configure receiver
                receiver.Open(DeviceMode.Promiscuous);
                receiver.Filter            = "ether proto 0x1234";
                receiver.OnPacketArrival  += Receiver_OnPacketArrival;
                receiver.OnCaptureStopped += Receiver_OnCaptureStopped;
                receiver.StartCapture();

                // Send the packets
                var packet = EthernetPacket.RandomPacket();
                packet.Type = (EthernetType)0x1234;
                for (var i = 0; i < PacketsCount; i++)
                {
                    sender.SendPacket(packet);
                }
                // Wait for packets to arrive
                Thread.Sleep(2000);
                receiver.StopCapture();
            }
            finally
            {
                receiver.OnPacketArrival -= Receiver_OnPacketArrival;
                sender.Close();
                receiver.Close();
            }
            // Checks
            Assert.That(packets, Has.Count.EqualTo(PacketsCount));
            Assert.That(statuses, Has.Count.EqualTo(1));
            Assert.AreEqual(statuses[0], CaptureStoppedEventStatus.CompletedWithoutError);
        }
Exemplo n.º 27
0
        /// <summary>
        /// Run a test routine, and report what packets were captured during that routine
        /// </summary>
        /// <param name="filter">to avoid noise from OS affecting test result, a filter is needed</param>
        /// <param name="routine">the routine to run</param>
        /// <returns></returns>
        internal static List <RawCapture> RunCapture(string filter, Action <PcapDevice> routine)
        {
            var device = GetPcapDevice();

            Console.WriteLine($"Using device {device}");
            var received = new List <RawCapture>();
            var mode     = RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ?
                           DeviceMode.Promiscuous :
                           DeviceMode.Normal;

            device.Open(mode, 1);
            device.Filter = filter;
            // We can't use the same device for capturing and sending in Linux
            // The device simply does not receive its own sent traffic in Linux, not sure what the reason is.
            // Tested using Linux on Windows WSL
            var sender = device;

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                sender = new LibPcapLiveDevice(device.Interface);
                sender.Open(mode, 1);
            }
            try
            {
                routine(sender);
                // waiting for any queued packets to be sent
                Thread.Sleep(10);
                var sw = Stopwatch.StartNew();
                while (true)
                {
                    var raw = device.GetNextPacket();
                    if (raw != null)
                    {
                        var packet = raw.GetPacket();
                        Console.WriteLine($"Received: {packet} after {sw.Elapsed} (at {raw.Timeval})");
                        received.Add(raw);
                    }
                    else
                    {
                        Console.WriteLine($"Received: null packet after {sw.Elapsed})");
                        if (sw.ElapsedMilliseconds > 1000)
                        {
                            // No more packets in queue, and 1 second has passed
                            break;
                        }
                    }
                }
            }
            finally
            {
                sender.Close();
                device.Close();
            }
            return(received);
        }
Exemplo n.º 28
0
        public static ICaptureDevice GetNcard(PhysicalAddress mac)
        {
            try
            {
                string osType = Environment.OSVersion.Platform.ToString();
                LibPcapLiveDeviceList allDev = LibPcapLiveDeviceList.Instance;
                LibPcapLiveDevice     device = allDev[0];
                _log.DebugFormat("Trying to get NIC by address {0}", mac.ToString());
                _log.Debug("List all device : ");
                foreach (LibPcapLiveDevice nCard in allDev)
                {
                    _log.DebugFormat("Name {0}. Address count :{1}", nCard.Name, nCard.Interface.Addresses.Count);
                    if (osType.ToUpper().Contains("WIN"))
                    {
                        //VLan enabled
                        if (nCard.Addresses.Count == 0)
                        {
                            device = nCard;
                            _log.Info("Get vlan nCard: " + device.Name);
                            break;
                        }

                        //VLan disabled
                        foreach (var addr in nCard.Addresses)
                        {
                            if (addr.Addr.hardwareAddress != null && mac.Equals(addr.Addr.hardwareAddress))
                            {
                                device = nCard;
                            }
                        }
                    }
                    else
                    {
                        if (!nCard.Name.Contains("."))
                        {
                            foreach (var addr in nCard.Addresses)
                            {
                                if (addr.Addr.hardwareAddress != null && mac.Equals(addr.Addr.hardwareAddress))
                                {
                                    device = nCard;
                                }
                            }
                        }
                    }
                }
                _log.DebugFormat("Get NIC : " + device.Name + " System is : " + osType);
                return(device);
            }
            catch (NullReferenceException ex)
            {
                Exception msg = new Exception("Can't Get Ncard");
                _log.Error("Have null ref, maybe macaddress in app.config incorrect Error is :" + ex.Message);
                throw msg;
            }
        }
Exemplo n.º 29
0
 public static void StopAndClose(this LibPcapLiveDevice device)
 {
     if (device.Started)
     {
         device.StopCapture();
     }
     if (device.Opened)
     {
         device.Close();
     }
 }
Exemplo n.º 30
0
        public void SendPacketsFromFile(LibPcapLiveDevice Device, string Path, bool?PeriodEn, int Period)
        {
            Device.Open();
            SendingThreadEnable = true;

            List <RawCapture> rawCaptures = new List <RawCapture>();

            try
            {
                RawCapture     packet;
                ICaptureDevice PacketsFile = OpenPacketsFile(Path);
                while ((packet = PacketsFile.GetNextPacket()) != null)
                {
                    rawCaptures.Add(packet);
                }
            }
            catch (Exception e)
            {
                basic.MessageBox(e.Message);
            }

            Thread td = new Thread(() =>
            {
                while (true)
                {
                    if (SendingThreadEnable == false)
                    {
                        break;
                    }

                    try
                    {
                        for (int i = 0; i < rawCaptures.Count; i++)
                        {
                            Device.SendPacket(rawCaptures[i].Data);
                        }
                    }
                    catch (Exception e)
                    {
                        basic.MessageBox(e.Message);
                    }
                    if (PeriodEn == true)
                    {
                        Thread.Sleep(Period);
                    }
                    else
                    {
                        break;
                    }
                }
            });

            td.Start();
        }