public FlowMeasureDevice(string ip)
        {
            localIP = ip;
            int currentDevice;

            var Devices = CaptureDeviceList.New();

            for (currentDevice = 0; currentDevice < Devices.Count; currentDevice++)
            {
                if (Devices[currentDevice].ToString().IndexOf(ip) != -1)
                {
                    break;
                }
            }

            SendDevice = (ICaptureDevice)CaptureDeviceList.New()[currentDevice];
            SendDevice.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrivalSend);
            SendDevice.Open(DeviceMode.Promiscuous, 1000);
            SendDevice.Filter = "src host " + ip;

            RecvDevice = (ICaptureDevice)CaptureDeviceList.New()[currentDevice];
            RecvDevice.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrivalRecv);
            RecvDevice.Open(DeviceMode.Promiscuous, 1000);
            RecvDevice.Filter = "dst host " + ip;

            NetSendBytes = 0;
            NetRecvBytes = 0;
            isUsed       = false;
        }
Esempio n. 2
0
        public void CaptureDeviceListNew()
        {
            var deviceList = CaptureDeviceList.New();

            Assert.IsNotNull(deviceList);
            Assert.IsNotEmpty(deviceList);
        }
Esempio n. 3
0
        /// <summary>
        /// A basic Wake-On-LAN capture example
        /// </summary>
        public static void Main()
        {
            // print SharpPcap version
            var ver = Pcap.SharpPcapVersion;

            Console.WriteLine("SharpPcap {0}", ver);

            // retrieve the device list
            var devices = CaptureDeviceList.Instance;

            // if no devices were found print an error
            if (devices.Count < 1)
            {
                Console.WriteLine("No devices were found on this machine");
                return;
            }

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

            int i = 0;

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

            Console.WriteLine();
            Console.Write("-- Please choose a device to capture: ");
            i = int.Parse(Console.ReadLine());

            using var device1 = devices[i];
            using var device2 = CaptureDeviceList.New()[i];

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

            // open the device for capturing
            int readTimeoutMilliseconds = 1000;

            device1.Open(DeviceModes.Promiscuous, readTimeoutMilliseconds);
            device2.Open(DeviceModes.Promiscuous, readTimeoutMilliseconds);

            // tcpdump filter to capture only TCP/IP packets
            device1.Filter = "ether dst FF:FF:FF:FF:FF:FF and udp";
            device2.Filter = "ether dst FF:FF:FF:FF:FF:FF and ether proto 0x0842";

            Console.WriteLine();
            Console.WriteLine("-- Listening for packets... Hit 'Ctrl-C' to exit --");

            // start capture packets
            device1.Capture();
            device2.Capture();
        }
Esempio n. 4
0
 public LimiterClass(Device device)
 {
     this.device   = device;
     capturedevice = CaptureDeviceList.New()[Properties.Settings.Default.AdapterName];
     TargetMAC     = GetClientList.GetMACString(device.MAC);
     GatewayMAC    = GetClientList.GetMACString(device.GatewayMAC);
 }
Esempio n. 5
0
        public void TestTwoCapture()
        {
            bool ipex = false, arpex = false;
            var  thread1 = new Thread(capture1 => {
                try {
                    var device = CaptureDeviceList.New()[2];
                    device.Open();
                    device.OnPacketArrival += Device_OnPacketArrival1;
                    device.Filter           = "ip";
                    device.StartCapture();
                    Thread.Sleep(30 * 1000);
                    device.OnPacketArrival -= Device_OnPacketArrival1;
                    device.StopCapture();
                    device.Close();
                }
                catch {
                    ipex = true;
                }
            });
            var thread2 = new Thread(capture2 => {
                try {
                    var device = CaptureDeviceList.New()[2];
                    device.Open();
                    device.OnPacketArrival += Device_OnPacketArrival2;
                    device.Filter           = "arp";
                    device.StartCapture();
                    Thread.Sleep(30 * 1000);
                    device.OnPacketArrival -= Device_OnPacketArrival2;
                    device.StopCapture();
                    device.Close();
                }
                catch {
                    arpex = true;
                }
            });

            thread1.Start();
            thread2.Start();
            while (thread1.IsAlive || thread2.IsAlive)
            {
                Thread.Sleep(1000);
            }
            if (ipex || arpex)
            {
                Trace.WriteLine("Exception happened.");
                return;
            }
            Trace.WriteLine("IP: " + _ip);
            Trace.WriteLine("ARP: " + _arp);

            /* 测试结果表明:
             *     同一个设备使用CaptureDeviceList.New()生成的不同实例
             * 在抓包时不会产生冲突,所有的Start、Stop、Open或是Close,
             * 甚至是绑定方法等等都视为独立设备,使用这种方法可以有效应
             * 用于多个线程使用不同过滤器同时抓包的场合。
             */
        }
Esempio n. 6
0
 public static CaptureDeviceList getInstance()
 {
     if (cdl == null)
     {
         //cdl = CaptureDeviceList.Instance;
         cdl = CaptureDeviceList.New();
     }
     return(cdl);
 }
Esempio n. 7
0
 private CaptureDeviceList _GetDeviceList()
 {
     try
     {
         return(CaptureDeviceList.New());
     }
     catch (DllNotFoundException ex)
     {
         throw new PeachException("Error, PcapMonitor was unable to get the device list.  Ensure libpcap is installed and try again.", ex);
     }
 }
Esempio n. 8
0
        private static void SetDevice(string name)
        {
            var device = CaptureDeviceList.New().FirstOrDefault(o => o.Name == name) as LibPcapLiveDevice;

            if (device == null)
            {
                Console.Error.WriteLine($"Bylo zadáno neplatné rozhraní.\nNápovědu vypíšete parametrem --help.");
                Environment.Exit(AppCodes.InvalidInterface);
            }

            Device = device;
        }
        private static void CaptureFlowSend(string IP, int portID, int deviceID)
        {
            ICaptureDevice device = CaptureDeviceList.New()[deviceID];

            device.OnPacketArrival += new PacketArrivalEventHandler(Device_OnPacketArrivalSend);
            int readTimeoutMilliseconds = 1000;

            device.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);
            string filter = "src host " + IP + " and src port " + portID;

            device.Filter = filter;
            device.StartCapture();
        }
Esempio n. 10
0
        public void CaptureFlowRecv(string IP, int portID, int deviceID)
        {
            ICaptureDevice device = CaptureDeviceList.New()[deviceID];

            device.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrivalRecv);
            int readTimeoutMilliseconds = 0;

            device.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);
            string filter = "dst host " + IP + " and dst port " + portID;

            device.Filter = filter;
            device.StartCapture();
            ProcInfo.CapDevs.Add(device);
        }
Esempio n. 11
0
        public void CaptureFlowSend(string IP, int deviceID)
        {
            ICaptureDevice device = (ICaptureDevice)CaptureDeviceList.New()[deviceID];

            device.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrivalSend);
            int readTimeoutMilliseconds = 100;

            device.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);
            string filter = "src host " + IP;

            device.Filter = filter;
            device.StartCapture();
            ProcInfo.CapDevs.Add(device);
        }
Esempio n. 12
0
        public static void Initialize(string filter)
        {
            try
            {
                if (!Initialized)
                {
                    devices = CaptureDeviceList.Instance;
                    if (devices.Count < 1)
                    {
                        Initialized = false;
                    }
                    else
                    {
                        int i = 0;
                        foreach (var dev in devices)
                        {
                            var dev1 = CaptureDeviceList.New()[i];
                            // Register our handler function to the 'packet arrival' event
                            dev.OnPacketArrival +=
                                new PacketArrivalEventHandler(device_OnPacketArrival);
                            dev1.OnPacketArrival +=
                                new PacketArrivalEventHandler(device1_OnPacketArrival);
                            // Open the device for capturing
                            int readTimeoutMilliseconds = 1000;
                            dev.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);
                            dev1.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);
                            dev.Filter = filter;

                            i++;
                        }
                        Initialized = true;
                    }
                }
            }
            catch (Exception ex)
            {
                Initialized = false;
                AntiCrash.LogException(ex);
            }
            finally
            {
            }
        }
Esempio n. 13
0
        public void GetReady()
        {
            if (!CaptureDeviceConfigured)
            {
                metroTextBox2.BeginInvoke(new Action(() =>
                {
                    metroTextBox2.Text += "Preparing network adapter..." + Environment.NewLine;
                }));

                CaptureDeviceList capturedevicelist = CaptureDeviceList.Instance;
                capturedevicelist.Refresh();
                capturedevice           = CaptureDeviceList.New()[NetStalker.Properties.Settings.Default.AdapterName];
                CaptureDeviceConfigured = true;

                metroTextBox2.BeginInvoke(new Action(() =>
                {
                    metroTextBox2.Text += "Ready" + Environment.NewLine;
                }));
            }
        }
        //tasks used by each constructor path
        private void init()
        {
            //not really sure what the capture device is, I think it refers to the NIC
            device = CaptureDeviceList.New()[3]; //better than .instance[3] apparently, according to author
            device.Open();                       //opens device, whatever that means

            //TCP packet is the payload of the IP packet
            //TcpPacket tcpPacket = new TcpPacket(localPort, destPort); //creates empty packet and sets the source and destination ports <port>
            //tcpPacket.Flags = 0x02; //syn flag
            //tcpPacket.WindowSize = 64240;
            UdpPacket udpPacket = new UdpPacket(localPort, destPort);



            //IP packet delivers TCP packet as its payload. IP packet is the payload of the Ethernet packet going to the gateway
            IPv4Packet ipPacket = new IPv4Packet(srcAddress, destAddress);

            ipPacket.TotalLength   = 52;
            ipPacket.Id            = 0xa144;
            ipPacket.FragmentFlags = 0x40;
            ipPacket.TimeToLive    = 128;

            //Ethernet packet delivers the IP packet to the gateway
            PhysicalAddress srcMAC = getLocalMAC();

            //Console.WriteLine(srcMAC); //just check that it is getting the right one, otherwise you'll have to enter it manually
            ethernetPacket = new EthernetPacket(srcMAC, destMAC, EthernetType.None);

            //matryoshka doll the packets
            ethernetPacket.PayloadPacket = ipPacket;
            ipPacket.PayloadPacket       = udpPacket;

            //this may need to be moved elsewhere incase time factors into the checksum
            udpPacket.Checksum = udpPacket.CalculateUdpChecksum();
            ipPacket.Checksum  = ipPacket.CalculateIPChecksum();


            sendTimer          = new Timer();
            sendTimer.Elapsed += new ElapsedEventHandler(sendPacket); //method to be done every interval
            sendTimer.Enabled  = true;                                //does not start timer, it means the method will be done every interval
        }
Esempio n. 15
0
        private static void Main()
        {
#if TEST_CONSOLE
            Test_in_Console();
#else
            // 初始化环境
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            // 检测WinPcap库
            try {
                CaptureDeviceList.New();
            }
            catch (Exception) {
                MessageBox.Show("本程序需要WinPcap支持,请确保WinPcap库正常工作!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            Application.Run(new MainPart());
#endif
        }
        private void scan_transfer_speed(String devicename, String ipadd)
        {
            CaptureDeviceList devices = CaptureDeviceList.New();

            foreach (WinPcapDevice d in devices)
            {
                if (d.Interface.FriendlyName == devicename)
                {
                    _device = d;
                    break;
                }
            }

            if (_device != null)
            {
                _device.OnPcapStatistics += new StatisticsModeEventHandler(update_statistics);
                _device.Open(DeviceMode.Promiscuous, 1000);
                _device.Filter = "(tcp or udp) and host " + ipadd;
                _device.Mode   = CaptureMode.Statistics;
                _device.StartCapture();
            }
        }
Esempio n. 17
0
        /// <summary>
        /// 从所有网卡上开始抓包
        /// </summary>
        public void startCapture()
        {
            Debug.WriteLine("[+]一个游戏( " + port + " )准备开始抓包...");
            this.bufferList = new List <RawCapture>();
            this.clear();         // 清理原有的数据
            this.isStartAnalyzer = true;
            this.startAnalyzer(); // 启动分析线程
            naList = new List <ICaptureDevice>();

            //foreach (ICaptureDevice device in CaptureDeviceManager.getInstance()) {
            var devices = CaptureDeviceManager.getInstance();

            for (int i = 0; i < devices.Count; i++)
            {
                if (devices[i].Description.Contains("VMware") || devices[i].Description.Contains("TAP-Windows Adapter"))
                {
                    Debug.WriteLine("[-]端口( " + port + " )在" + devices[i].Description + " 已忽略...");
                    continue; //跳过虚拟网卡和SS-TAP
                }
                // 这里必须使用CaptureDeviceList.New()[i]获取新实例, 虽然很慢, 但是没有解决办法
                // 如果使用devices[i] 那表示使用的还是同一块网卡, 绑定多个过滤器, 并不是多网卡实例 会导致多个Game收到同样的内容
                ICaptureDevice device = CaptureDeviceList.New()[i];
                //ICaptureDevice device = devices[i];

                try {
                    device.OnPacketArrival += new PacketArrivalEventHandler(this.device_OnPacketArrival);
                    device.Open(Settings.devMode, Settings.readTimeOut);
                    device.Filter = "port " + this.port;
                    device.StartCapture();
                } catch (Exception ex) {
                    MessageBox.Show(ex.Message);
                }
                naList.Add(device);
                Debug.WriteLine("[+]端口( " + port + " )在" + device.Description + " 初始化完毕...");
            }
            this.isStartMonitor = true;
            this.startMonitor();// 启动掉线监测
            Debug.WriteLine("[+]一个游戏( " + port + " )抓包已启动完毕...");
        }
Esempio n. 18
0
        public static CaptureDeviceList GetDevice()
        {
            var devices = CaptureDeviceList.New();

            if (devices.Count < 1)
            {
                return(null);
            }
            Regex r = new Regex("FriendlyName:(.+)");
            int   i = 0;

            OutPut("List of Current Adapters.Modify the adapter index to capture.");
            foreach (var d in devices)
            {
                string info         = d.ToString();
                string friendlyName = r.Match(info).Groups[1].Value;
                OutPut("[" + i + "] " + friendlyName);
                //OutPut(d.ToString());
                i++;
            }
            OutPut("------------------------------------------------------------");
            return(devices);
        }
Esempio n. 19
0
        public static void Process()
        {
            var devices = CaptureDeviceList.New();

            foreach (var device in devices.OfType <LibPcapLiveDevice>())
            {
                try
                {
                    device.Open(DeviceMode.Promiscuous);

                    var builder = new StringBuilder()
                                  .Append("Name: ").AppendLine(device.Name);

                    if (!string.IsNullOrEmpty(device.Interface.FriendlyName) && device.Interface.FriendlyName != device.Name)
                    {
                        builder.Append("FriendlyName: ").AppendLine(device.Interface.FriendlyName);
                    }

                    var ipv4Adresses = device.Interface.Addresses.Where(IsIPV4).ToList();
                    var ipv6Adresses = device.Interface.Addresses.Where(IsIPV6).ToList();

                    if (ipv4Adresses.Count == 0 || ipv6Adresses.Count == 0)
                    {
                        continue;
                    }

                    if (ipv4Adresses.Count > 0)
                    {
                        builder.Append("Addresses (IPv4): ").AppendLine(string.Join(", ", ipv4Adresses.Select(FormatIPAddress).Where(o => o != null)));
                    }
                    if (ipv6Adresses.Count > 0)
                    {
                        builder.Append("Addresses (IPv6): ").AppendLine(string.Join(", ", ipv6Adresses.Select(FormatIPAddress).Where(o => o != null)));
                    }

                    var ipv4GatewayAddresses = device.Interface.GatewayAddresses?.Where(IsIPV4).ToList() ?? new List <IPAddress>();
                    var ipv6GatewayAddresses = device.Interface.GatewayAddresses?.Where(IsIPV6).ToList() ?? new List <IPAddress>();

                    if (ipv4GatewayAddresses.Count > 0)
                    {
                        builder.Append("Gateway addresses (IPv4): ").AppendLine(string.Join(", ", ipv4GatewayAddresses.Select(o => o.ToString())));
                    }
                    if (ipv6GatewayAddresses.Count > 0)
                    {
                        builder.Append("Gateway addresses (IPv6): ").AppendLine(string.Join(", ", ipv6GatewayAddresses.Select(o => o.ToString())));
                    }

                    Console.WriteLine(builder.ToString());
                }
                catch (PcapException)
                {
                    // Pro účely zjištění seznamu aktivních rozhraní je vyjímka zbytečná.
                    continue;
                }
                finally
                {
                    if (device.Opened)
                    {
                        device.Close();
                    }
                }
            }
        }
Esempio n. 20
0
        public static void Main(string[] args)
        {
            // Print SharpPcap version
            string ver = SharpPcap.Version.VersionString;

            Console.WriteLine("SharpPcap {0}, MultipleFiltersOnDevice", ver);

            // If no devices were found print an error
            if (CaptureDeviceList.Instance.Count < 1)
            {
                Console.WriteLine("No devices were found on this machine");
                return;
            }

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

            int i = 0;

            // Print out the devices
            foreach (var dev in CaptureDeviceList.Instance)
            {
                /* Description */
                Console.WriteLine("{0}) {1} {2}", i, dev.Name, dev.Description);
                i++;
            }

            Console.WriteLine();
            Console.Write("-- Please choose a device to capture: ");
            i = int.Parse(Console.ReadLine());

            int readTimeoutMilliseconds = 1000;

            var device1 = CaptureDeviceList.Instance[i];
            var device2 = CaptureDeviceList.New()[i];             // NOTE: the call to New()

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

            // Open the devices for capturing
            device1.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);
            device2.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);

            // set the filters
            device1.Filter = "tcp port 80";             // http
            device2.Filter = "udp port 53";             // dns

            Console.WriteLine("device1.Filter {0}, device2.Filter {1}",
                              device1.Filter, device2.Filter);

            Console.WriteLine();
            Console.WriteLine("-- Listening on {0} {1}, hit 'Enter' to stop...",
                              device1.Name, device1.Description);

            // Start the capturing process
            device1.StartCapture();
            device2.StartCapture();

            // Wait for 'Enter' from the user.
            Console.ReadLine();

            // Stop the capturing process
            device1.StopCapture();
            device2.StopCapture();

            Console.WriteLine("-- Capture stopped.");

            // Print out the device statistics
            Console.WriteLine("device1 {0}", device1.Statistics.ToString());
            Console.WriteLine("device2 {0}", device2.Statistics.ToString());

            // Close the pcap device
            device1.Close();
            device2.Close();
        }
Esempio n. 21
0
        /// <summary>
        /// This is the main method for blocking and redirection of targeted devices.
        /// </summary>
        public static void BlockAndRedirect()
        {
            if (!BRMainSwitch)
            {
                throw new InvalidOperationException("\"BRMainSwitch\" must be set to \"True\" in order to activate the BR");
            }

            if (string.IsNullOrEmpty(Properties.Settings.Default.GatewayMac))
            {
                Properties.Settings.Default.GatewayMac = Main.Devices.Where(d => d.Key.Equals(AppConfiguration.GatewayIp)).Select(d => d.Value.MAC).FirstOrDefault().ToString();
                Properties.Settings.Default.Save();
            }

            if (BRDevice == null)
            {
                BRDevice = (LibPcapLiveDevice)CaptureDeviceList.New()[AppConfiguration.AdapterName];
            }

            BRDevice.Open(DeviceModes.Promiscuous, 1000);
            BRDevice.Filter = "ip";

            BRTask = Task.Run(() =>
            {
                RawCapture rawCapture;
                EthernetPacket packet;

                while (BRMainSwitch)
                {
                    if (BRDevice.GetNextPacket(out PacketCapture packetCapture) == GetPacketStatus.PacketRead)
                    {
                        rawCapture = packetCapture.GetPacket();
                        packet     = Packet.ParsePacket(rawCapture.LinkLayerType, rawCapture.Data) as EthernetPacket;

                        if (packet == null)
                        {
                            continue;
                        }

                        Device device;

                        if ((device = Main.Devices.FirstOrDefault(D => D.Value.MAC.Equals(packet.SourceHardwareAddress)).Value) != null && device.Redirected && !device.IsLocalDevice && !device.IsGateway)
                        {
                            if (device.UploadCap == 0 || device.UploadCap > device.PacketsSentSinceLastReset)
                            {
                                packet.SourceHardwareAddress      = BRDevice.MacAddress;
                                packet.DestinationHardwareAddress = AppConfiguration.GatewayMac;
                                BRDevice.SendPacket(packet);
                                device.PacketsSentSinceLastReset += packet.Bytes.Length;
                            }
                        }
                        else if (packet.SourceHardwareAddress.Equals(AppConfiguration.GatewayMac))
                        {
                            IPv4Packet IPV4 = packet.Extract <IPv4Packet>();

                            if (Main.Devices.TryGetValue(IPV4.DestinationAddress, out device) && device.Redirected && !device.IsLocalDevice && !device.IsGateway)
                            {
                                if (device.DownloadCap == 0 || device.DownloadCap > device.PacketsReceivedSinceLastReset)
                                {
                                    packet.SourceHardwareAddress      = BRDevice.MacAddress;
                                    packet.DestinationHardwareAddress = device.MAC;
                                    BRDevice.SendPacket(packet);
                                    device.PacketsReceivedSinceLastReset += packet.Bytes.Length;
                                }
                            }
                        }
                    }

                    SpoofClients();
                }
            });
        }
Esempio n. 22
0
        public static void BackgroundScanStart(IView view, string interfacefriendlyname)
        {
            try
            {
                view.MainForm.BeginInvoke(new Action(() => view.StatusLabel.Text = "Starting background scan..."));
                StopFlag      = false;
                capturedevice = CaptureDeviceList.New()[NetStalker.Properties.Settings.Default.AdapterName];
                capturedevice.Open(DeviceMode.Promiscuous, 1000);
                capturedevice.Filter = "arp";


                IPAddress myipaddress = IPAddress.Parse(NetStalker.Properties.Settings.Default.localip);
                Size = NetStalker.Properties.Settings.Default.NetMask.Count(c => c == '0');
                var Root = GetRoot(myipaddress, Size);

                #region Sending ARP requests to probe for all possible IP addresses on LAN
                new Thread(() =>
                {
                    Thread.Sleep(5000);

                    try
                    {
                        view.PictureBox.BeginInvoke(new Action((() =>
                        {
                            view.PictureBox.Image = NetStalker.Properties.Resources.icons8_ok_96px;
                        })));
                        view.StatusLabel2.BeginInvoke(new Action(() => { view.StatusLabel2.Text = "Ready"; }));

                        view.MainForm.BeginInvoke(new Action(() =>
                        {
                            view.Tile.Enabled  = true;
                            view.Tile2.Enabled = true;
                        }));

                        while (capturedevice != null && !StopFlag)
                        {
                            if (Size == 1)
                            {
                                try
                                {
                                    if (!LoadingBarCalled)
                                    {
                                        CallTheLoadingBar(view);
                                        Main.checkboxcanbeclicked = true;
                                        view.MainForm.BeginInvoke(new Action(() => view.StatusLabel.Text = "Scanning..."));
                                    }

                                    for (int ipindex = 1; ipindex <= 255; ipindex++)
                                    {
                                        if (!StopFlag)
                                        {
                                            ARPPacket arprequestpacket    = new ARPPacket(ARPOperation.Request, PhysicalAddress.Parse("00-00-00-00-00-00"), IPAddress.Parse(Root + ipindex), capturedevice.MacAddress, myipaddress);
                                            EthernetPacket ethernetpacket = new EthernetPacket(capturedevice.MacAddress, PhysicalAddress.Parse("FF-FF-FF-FF-FF-FF"), EthernetPacketType.Arp);
                                            ethernetpacket.PayloadPacket  = arprequestpacket;
                                            capturedevice.SendPacket(ethernetpacket);
                                            if (NetStalker.Properties.Settings.Default.SpoofProtection)
                                            {
                                                ARPPacket ArpPacketForGatewayProtection        = new ARPPacket(ARPOperation.Request, capturedevice.MacAddress, myipaddress, GatewayMAC, GatewayIP);
                                                EthernetPacket EtherPacketForGatewayProtection = new EthernetPacket(GatewayMAC, capturedevice.MacAddress, EthernetPacketType.Arp);
                                                EtherPacketForGatewayProtection.PayloadPacket  = ArpPacketForGatewayProtection;
                                                capturedevice.SendPacket(EtherPacketForGatewayProtection);
                                            }
                                        }
                                    }
                                }
                                catch (Exception)
                                {
                                }
                            }

                            else if (Size == 2)
                            {
                                try
                                {
                                    if (!LoadingBarCalled)
                                    {
                                        CallTheLoadingBar(view);
                                        Main.checkboxcanbeclicked = true;
                                        view.MainForm.BeginInvoke(new Action(() => view.StatusLabel.Text = "Scanning..."));
                                    }
                                    for (int i = 1; i <= 255; i++)
                                    {
                                        if (!StopFlag)
                                        {
                                            for (int j = 1; j <= 255; j++)
                                            {
                                                if (!StopFlag)
                                                {
                                                    ARPPacket arprequestpacket    = new ARPPacket(ARPOperation.Request, PhysicalAddress.Parse("00-00-00-00-00-00"), IPAddress.Parse(Root + i + '.' + j), capturedevice.MacAddress, myipaddress);//???
                                                    EthernetPacket ethernetpacket = new EthernetPacket(capturedevice.MacAddress, PhysicalAddress.Parse("FF-FF-FF-FF-FF-FF"), EthernetPacketType.Arp);
                                                    capturedevice.SendPacket(ethernetpacket);
                                                    if (NetStalker.Properties.Settings.Default.SpoofProtection)
                                                    {
                                                        ARPPacket ArpPacketForGatewayProtection        = new ARPPacket(ARPOperation.Request, capturedevice.MacAddress, myipaddress, GatewayMAC, GatewayIP);
                                                        EthernetPacket EtherPacketForGatewayProtection = new EthernetPacket(GatewayMAC, capturedevice.MacAddress, EthernetPacketType.Arp);
                                                        EtherPacketForGatewayProtection.PayloadPacket  = ArpPacketForGatewayProtection;
                                                        capturedevice.SendPacket(EtherPacketForGatewayProtection);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                catch (Exception)
                                {
                                }
                            }

                            else if (Size == 3)
                            {
                                try
                                {
                                    if (!LoadingBarCalled)
                                    {
                                        CallTheLoadingBar(view);
                                        Main.checkboxcanbeclicked = true;
                                        view.MainForm.BeginInvoke(new Action(() => view.StatusLabel.Text = "Scanning..."));
                                    }
                                    for (int i = 1; i <= 255; i++)
                                    {
                                        if (!StopFlag)
                                        {
                                            for (int j = 1; j <= 255; j++)
                                            {
                                                if (!StopFlag)
                                                {
                                                    for (int k = 1; k <= 255; k++)
                                                    {
                                                        if (!StopFlag)
                                                        {
                                                            ARPPacket arprequestpacket    = new ARPPacket(ARPOperation.Request, PhysicalAddress.Parse("00-00-00-00-00-00"), IPAddress.Parse(Root + i + '.' + j + '.' + k), capturedevice.MacAddress, myipaddress);//???
                                                            EthernetPacket ethernetpacket = new EthernetPacket(capturedevice.MacAddress, PhysicalAddress.Parse("FF-FF-FF-FF-FF-FF"), EthernetPacketType.Arp);
                                                            ethernetpacket.PayloadPacket  = arprequestpacket;
                                                            capturedevice.SendPacket(ethernetpacket);
                                                            if (NetStalker.Properties.Settings.Default.SpoofProtection)
                                                            {
                                                                ARPPacket ArpPacketForGatewayProtection        = new ARPPacket(ARPOperation.Request, capturedevice.MacAddress, myipaddress, GatewayMAC, GatewayIP);
                                                                EthernetPacket EtherPacketForGatewayProtection = new EthernetPacket(GatewayMAC, capturedevice.MacAddress, EthernetPacketType.Arp);
                                                                EtherPacketForGatewayProtection.PayloadPacket  = ArpPacketForGatewayProtection;
                                                                capturedevice.SendPacket(EtherPacketForGatewayProtection);
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                catch (Exception)
                                {
                                }
                            }
                        }
                    }
                    catch (Exception)
                    {
                    }
                }).Start();
                #endregion

                #region Assign OnPacketArrival event handler and start capturing
                capturedevice.OnPacketArrival += (object sender, CaptureEventArgs e) =>
                {
                    try
                    {
                        if (StopFlag)
                        {
                            return;
                        }
                        Packet packet = Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data);
                        if (packet == null)
                        {
                            return;
                        }
                        ARPPacket arppacket = (ARPPacket)packet.Extract(typeof(ARPPacket));

                        if (!clientlist.ContainsKey(arppacket.SenderProtocolAddress) && arppacket.SenderProtocolAddress.ToString() != "0.0.0.0" && areCompatibleIPs(arppacket.SenderProtocolAddress, myipaddress, Size))
                        {
                            clientlist.Add(arppacket.SenderProtocolAddress, arppacket.SenderHardwareAddress);
                            view.ListView1.Invoke(new Action(() =>
                            {
                                string mac = GetMACString(arppacket.SenderHardwareAddress);
                                int id     = clientlist.Count - 1;
                                string ip  = arppacket.SenderProtocolAddress.ToString();
                                var obj    = new Device();
                                new Thread(() =>
                                {
                                    try
                                    {
                                        ipp = ip;

                                        IPHostEntry hostEntry = Dns.GetHostEntry(ip);

                                        view.ListView1.BeginInvoke(new Action(() =>
                                        {
                                            obj.DeviceName = hostEntry.HostName;
                                            view.ListView1.UpdateObject(obj);
                                        }));
                                    }
                                    catch (Exception)
                                    {
                                        try
                                        {
                                            view.ListView1.BeginInvoke(new Action(() =>
                                            {
                                                obj.DeviceName = ip;
                                                view.ListView1.UpdateObject(obj);
                                            }));
                                        }
                                        catch (Exception)
                                        {
                                        }
                                    }
                                }).Start();

                                new Thread(() =>
                                {
                                    try
                                    {
                                        var Name = VendorAPI.GetVendorInfo(mac);
                                        if (Name != null)
                                        {
                                            obj.ManName = Name.data.organization_name;
                                        }
                                        else
                                        {
                                            obj.ManName = "";
                                        }
                                        view.ListView1.UpdateObject(obj);
                                    }
                                    catch (Exception)
                                    {
                                    }
                                }).Start();

                                obj.IP           = arppacket.SenderProtocolAddress;
                                obj.MAC          = PhysicalAddress.Parse(mac.Replace(":", ""));
                                obj.DeviceName   = "Resolving";
                                obj.ManName      = "Getting information...";
                                obj.DeviceStatus = "Online";
                                view.ListView1.AddObject(obj);
                            }));
                            view.MainForm.Invoke(new Action(() => view.StatusLabel.Text = clientlist.Count + " device(s) found"));
                        }
                        else if (clientlist.ContainsKey(arppacket.SenderProtocolAddress))
                        {
                            foreach (Device Device in view.ListView1.Objects)
                            {
                                if (Device.IP.Equals(arppacket.SenderProtocolAddress))
                                {
                                    Device.TimeSinceLastArp = DateTime.Now;
                                    break;
                                }
                            }
                        }
                    }
                    catch (Exception)
                    {
                    }
                };

                capturedevice.StartCapture();

                view.MainForm.Invoke(new Action(() => view.StatusLabel.Text = clientlist.Count + " device(s) found"));

                #endregion
            }
            catch (Exception)
            {
            }
        }