public void ReceivePackets()
            {
                // Retrieve the device list from the local machine
                IList<LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine;

                // Find the NPF device of the TAP interface
                PacketDevice selectedDevice = null;
                for (int i = 0; i != allDevices.Count; ++i)
                {
                    LivePacketDevice device = allDevices[i];
                    if (device.Name.Contains(Guid))
                    {
                        selectedDevice = device;
                        break;
                    }
                }

                if (selectedDevice == null)
                {
                    Initialized.Set();
                    Global.ShowTrayTip("Byte Counter", "Interface " + Name + " not captured by WinPcap.", System.Windows.Forms.ToolTipIcon.Warning);
                    Global.WriteLog("Byte Counter: Interface " + Name + " not captured by WinPcap.");
                    return;
                }

                try
                {
                    using (communicator = selectedDevice.Open(65536, PacketDeviceOpenAttributes.MaximumResponsiveness, 1000))
                    {
                        Global.WriteLog("Byte Counter: Listening on " + Name + "...");
                        communicator.SetFilter("((ether dst " + ifHardwareAddressString + " or ether src " + ifHardwareAddressString + ") and ip and (tcp or udp))");
                        Initialized.Set();
                        communicator.ReceivePackets(0, (packet) =>
                        {
                            if (!threadActive.IsSet)
                            {
                                communicator.Break();
                                return;
                            }
                            Table.CheckPacket(packet, ifHardwareAddress);
                        });
                    }
                }
                catch (Exception e)
                {
                    if (threadActive.IsSet)
                    {
                        threadActive.Reset();
                        Global.WriteLog("Byte Counter: Could not capture traffic from " + Name);
                        if (Global.Config.Gadget.Debug)
                            Global.WriteLog(e.ToString());
                        Global.ShowTrayTip("Byte Counter", "Could not capture traffic from " + Name, System.Windows.Forms.ToolTipIcon.Warning);
                    }
                }
            }
            public void ReceivePackets()
            {
                // Retrieve the device list from the local machine
                IList<LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine;

                // Find the NPF device of the TAP interface
                PacketDevice selectedDevice = null;
                for (int i = 0; i != allDevices.Count; ++i)
                {
                    LivePacketDevice device = allDevices[i];
                    if (device.Name.ToUpper().Contains(Guid.ToString().ToUpper()))
                    {
                        selectedDevice = device;
                        break;
                    }
                }

                if (selectedDevice == null)
                {
                    Initialized.Set();
                    Global.ShowTrayTip("Load Balancer", "Interface " + Name + " not captured by WinPcap.", System.Windows.Forms.ToolTipIcon.Warning);
                    Global.WriteLog("Load Balancer: Interface " + Name + " not captured by WinPcap.");
                    return;
                }

                try
                {
                    using (communicator = selectedDevice.Open(65536, PacketDeviceOpenAttributes.MaximumResponsiveness, 1000))
                    {
                        Global.WriteLog("Load Balancer: Listening on " + Name + "...");
                        communicator.SetFilter("(ether dst " + ownHardwareAddressString + " and ((ip and (tcp or udp or icmp)) or arp)) or (ether dst FF:FF:FF:FF:FF:FF and arp)");
                        Initialized.Set();
                        communicator.ReceivePackets(0, (packet) =>
                        {
                            if (!ThreadActive.IsSet)
                            {
                                communicator.Break();
                                return;
                            }
                            if (packet.Ethernet.EtherType == EthernetType.Arp)
                            {
                                if (packet.Ethernet.Arp.TargetProtocolAddress.SequenceEqual(ownProtocolAddressByte) && packet.Ethernet.Arp.Operation == ArpOperation.Request)
                                {
                                    EthernetLayer ethernetLayer = new EthernetLayer
                                    {
                                        Source = ownHardwareAddress,
                                        Destination = packet.Ethernet.Source,
                                        EtherType = EthernetType.None,
                                    };

                                    ArpLayer arpLayer = new ArpLayer
                                    {
                                        ProtocolType = EthernetType.IpV4,
                                        Operation = ArpOperation.Reply,
                                        SenderHardwareAddress = ownHardwareAddressByte.AsReadOnly(),
                                        SenderProtocolAddress = packet.Ethernet.Arp.TargetProtocolAddress,
                                        TargetHardwareAddress = packet.Ethernet.Arp.SenderHardwareAddress,
                                        TargetProtocolAddress = packet.Ethernet.Arp.SenderProtocolAddress,
                                    };

                                    PacketBuilder builder = new PacketBuilder(ethernetLayer, arpLayer);
                                    SendPacket(builder.Build(DateTime.Now));
                                }
                            }
                            else if (packet.Ethernet.EtherType.ToString() == "IpV4")
                            {

                                if (packet.Ethernet.IpV4.Fragmentation.Options == IpV4FragmentationOptions.DoNotFragment ||
                                    packet.Ethernet.IpV4.Fragmentation.Options == IpV4FragmentationOptions.None && packet.Ethernet.IpV4.Fragmentation.Offset == 0)
                                {
                                    IpV4Handler(packet);
                                }
                                else if (packet.Ethernet.IpV4.Fragmentation.Options == IpV4FragmentationOptions.MoreFragments ||
                                    packet.Ethernet.IpV4.Fragmentation.Options == IpV4FragmentationOptions.None && packet.Ethernet.IpV4.Fragmentation.Offset > 0)
                                {
                                    // TODO: fix warning spam
                                    if (Global.Config.LoadBalancer.ShowTrayTipsWarnings)
                                        Global.ShowTrayTip("Load Balancer", "IP fragmentation detected on " + Name + ".\n\nIP fragmentation is not supported.", ToolTipIcon.Warning);
                                    Global.WriteLog("Load Balancer: IP fragmentation detected on " + Name);
                                    //fragments = fragBuffer.Add(packet);
                                    //if (fragments != null)
                                    //    for (int i = 0; i < fragments.Count; i++)
                                    //    {
                                    //        IpV4Handler(fragments[i], fragments);
                                    //    }
                                }
                            }
                        });
                    }
                }
                catch (Exception e)
                {
                    if (ThreadActive.IsSet)
                    {
                        ThreadActive.Reset();
                        Global.WriteLog("Load Balancer: " + Name + " has disconnected");
                        if (Global.Config.Gadget.Debug)
                            Global.WriteLog(e.ToString());
                        Global.ShowTrayTip("Load Balancer", Name + " has disconnected", System.Windows.Forms.ToolTipIcon.Warning);
                    }
                }
            }
Exemple #3
0
        private static void TestGetStatistics(string sourceMac, string destinationMac, int numPacketsToSend, int numStatisticsToGather, int numStatisticsToBreakLoop, double secondsToWait, int packetSize,
                                              PacketCommunicatorReceiveResult expectedResult, int expectedNumStatistics, int expectedNumPackets, double expectedMinSeconds, double expectedMaxSeconds)
        {
            using (PacketCommunicator communicator = OpenLiveDevice())
            {
                communicator.Mode = PacketCommunicatorMode.Statistics;

                communicator.SetFilter("ether src " + sourceMac + " and ether dst " + destinationMac);

                Packet sentPacket = _random.NextEthernetPacket(packetSize, sourceMac, destinationMac);

                PacketCommunicatorReceiveResult result = PacketCommunicatorReceiveResult.None;
                int   numStatisticsGot = 0;
                ulong totalPackets     = 0;
                ulong totalBytes       = 0;
                for (int i = 0; i != numPacketsToSend; ++i)
                {
                    communicator.SendPacket(sentPacket);
                }

                if (numStatisticsToBreakLoop == 0)
                {
                    communicator.Break();
                }
                Thread thread = new Thread(delegate()
                {
                    result = communicator.ReceiveStatistics(numStatisticsToGather,
                                                            delegate(PacketSampleStatistics statistics)
                    {
                        Assert.IsNotNull(statistics.ToString());
                        totalPackets += statistics.AcceptedPackets;
                        totalBytes   += statistics.AcceptedBytes;
                        ++numStatisticsGot;
                        if (numStatisticsGot >= numStatisticsToBreakLoop)
                        {
                            communicator.Break();
                        }
                    });
                });

                DateTime startWaiting = DateTime.Now;
                thread.Start();

                if (!thread.Join(TimeSpan.FromSeconds(secondsToWait)))
                {
                    thread.Abort();
                }
                DateTime finishedWaiting = DateTime.Now;
                Assert.AreEqual(expectedResult, result, "Result");
                Assert.AreEqual(expectedNumStatistics, numStatisticsGot, "NumStatistics");
                Assert.AreEqual((ulong)expectedNumPackets, totalPackets, "NumPackets");
                // Todo check byte statistics. See http://www.winpcap.org/pipermail/winpcap-users/2015-February/004931.html
//                Assert.AreEqual((ulong)(numPacketsToSend * sentPacket.Length), totalBytes, "NumBytes");
                MoreAssert.IsInRange(expectedMinSeconds, expectedMaxSeconds, (finishedWaiting - startWaiting).TotalSeconds);
            }
        }
Exemple #4
0
        void FormMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (comm != null)
            {
                comm.Break();
                comm.Dispose();
                comm = null;
            }

            Ignores.I.Save();
            Settings.I.Save();
            stop = true;
        }
Exemple #5
0
        /// <summary>
        /// Stop capture and return the number of captured packets
        /// </summary>
        /// <returns></returns>
        public uint StopCapture()
        {
            communicator.Break();
            PacketTotalStatistics statistics = communicator.TotalStatistics;

            return(statistics.PacketsCaptured);
        }
Exemple #6
0
 public void Break()
 {
     if (_communicator != null)
     {
         _communicator.Break();
     }
 }
Exemple #7
0
 private static void OnAbortExecution()
 {
     if (__communicator != null)
     {
         __communicator.Break();
     }
 }
Exemple #8
0
        private static void TestGetSomePackets(int numPacketsToSend, int numPacketsToGet, int numPacketsToBreakLoop,
                                               PacketCommunicatorReceiveResult expectedResult, int expectedNumPackets,
                                               double expectedMinSeconds, double expectedMaxSeconds)
        {
            string testDescription = "NumPacketsToSend=" + numPacketsToSend + ". NumPacketsToGet=" + numPacketsToGet +
                                     ". NumPacketsToBreakLoop=" + numPacketsToBreakLoop;

            const string SourceMac      = "11:22:33:44:55:66";
            const string DestinationMac = "77:88:99:AA:BB:CC";

            Packet expectedPacket = _random.NextEthernetPacket(100, SourceMac, DestinationMac);

            using (PacketCommunicator communicator = OpenOfflineDevice(numPacketsToSend, expectedPacket))
            {
                communicator.SetFilter("ether src " + SourceMac + " and ether dst " + DestinationMac);

                if (numPacketsToBreakLoop == 0)
                {
                    communicator.Break();
                }
                PacketHandler handler = new PacketHandler(expectedPacket, expectedMinSeconds, expectedMaxSeconds, communicator, numPacketsToBreakLoop);

                int numPacketsGot;
                PacketCommunicatorReceiveResult result = communicator.ReceiveSomePackets(out numPacketsGot, numPacketsToGet, handler.Handle);
                Assert.AreEqual(expectedResult, result);
                Assert.AreEqual(expectedNumPackets, numPacketsGot, "NumPacketsGot. Test: " + testDescription);
                Assert.AreEqual(expectedNumPackets, handler.NumPacketsHandled, "NumPacketsHandled. Test: " + testDescription);
            }
        }
            public void ReceivePackets()
            {
                // Retrieve the device list from the local machine
                IList <LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine;

                // Find the NPF device of the TAP interface
                PacketDevice selectedDevice = null;

                for (int i = 0; i != allDevices.Count; ++i)
                {
                    LivePacketDevice device = allDevices[i];
                    if (device.Name.Contains(Guid))
                    {
                        selectedDevice = device;
                        break;
                    }
                }

                if (selectedDevice == null)
                {
                    Initialized.Set();
                    Global.ShowTrayTip("Byte Counter", "Interface " + Name + " not captured by WinPcap.", System.Windows.Forms.ToolTipIcon.Warning);
                    Global.WriteLog("Byte Counter: Interface " + Name + " not captured by WinPcap.");
                    return;
                }

                try
                {
                    using (communicator = selectedDevice.Open(65536, PacketDeviceOpenAttributes.MaximumResponsiveness, 1000))
                    {
                        Global.WriteLog("Byte Counter: Listening on " + Name + "...");
                        communicator.SetFilter("((ether dst " + ifHardwareAddressString + " or ether src " + ifHardwareAddressString + ") and ip and (tcp or udp))");
                        Initialized.Set();
                        communicator.ReceivePackets(0, (packet) =>
                        {
                            if (!threadActive.IsSet)
                            {
                                communicator.Break();
                                return;
                            }
                            Table.CheckPacket(packet, ifHardwareAddress);
                        });
                    }
                }
                catch (Exception e)
                {
                    if (threadActive.IsSet)
                    {
                        threadActive.Reset();
                        Global.WriteLog("Byte Counter: Could not capture traffic from " + Name);
                        if (Global.Config.Gadget.Debug)
                        {
                            Global.WriteLog(e.ToString());
                        }
                        Global.ShowTrayTip("Byte Counter", "Could not capture traffic from " + Name, System.Windows.Forms.ToolTipIcon.Warning);
                    }
                }
            }
Exemple #10
0
        private static void TestReceivePacketsEnumerable(int numPacketsToSend, int numPacketsToWait, int numPacketsToBreakLoop, double secondsToWait,
                                                         int packetSize, int expectedNumPackets, double expectedMinSeconds, double expectedMaxSeconds)
        {
            string testDescription = "NumPacketsToSend=" + numPacketsToSend + ". NumPacketsToWait=" + numPacketsToWait +
                                     ". NumPacketsToBreakLoop=" + numPacketsToBreakLoop + ". SecondsToWait=" +
                                     secondsToWait + ". PacketSize=" + packetSize;


            const string SourceMac      = "11:22:33:44:55:66";
            const string DestinationMac = "77:88:99:AA:BB:CC";

            using (PacketCommunicator communicator = OpenLiveDevice())
            {
                communicator.SetFilter("ether src " + SourceMac + " and ether dst " + DestinationMac);

                Packet sentPacket = _random.NextEthernetPacket(packetSize, SourceMac, DestinationMac);

                for (int i = 0; i != numPacketsToSend; ++i)
                {
                    communicator.SendPacket(sentPacket);
                }

                int    actualPacketsReceived = 0;
                Thread thread = new Thread(delegate()
                {
                    if (numPacketsToBreakLoop == 0)
                    {
                        communicator.Break();
                    }
                    IEnumerable <Packet> packets = numPacketsToWait == -1
                                                      ? communicator.ReceivePackets()
                                                      : communicator.ReceivePackets(numPacketsToWait);
                    foreach (Packet packet in packets)
                    {
                        Assert.AreEqual(sentPacket, packet);
                        ++actualPacketsReceived;
                        if (actualPacketsReceived == numPacketsToBreakLoop)
                        {
                            break;
                        }
                    }
                });

                DateTime startWaiting = DateTime.Now;
                thread.Start();

                if (!thread.Join(TimeSpan.FromSeconds(secondsToWait)))
                {
                    thread.Abort();
                }
                DateTime finishedWaiting = DateTime.Now;

                Assert.AreEqual(expectedNumPackets, actualPacketsReceived, testDescription);
                MoreAssert.IsInRange(expectedMinSeconds, expectedMaxSeconds, (finishedWaiting - startWaiting).TotalSeconds, testDescription);
            }
        }
Exemple #11
0
 public void Close()
 {
     startDone.WaitOne();
     if (communicator != null)
     {
         communicator.Break();
         communicator.Dispose();
         communicator = null;
     }
     pspsigCheck.Abort();
 }
Exemple #12
0
        public void Stop()
        {
            if (_packet_process_thread != null && _packet_process_thread.IsAlive)
            {
                _packet_communicator.Break();
                _packet_process_thread.Join();
                _packet_process_thread = null;

                _adapter_hashtable.Clear();
                _adapter_hashtable = null;
            }
        }
        internal static void Stop()
        {
            if (!_started)
            {
                return;
            }

            _communicator.Break();
            _timer1.Stop();
            _server.Stop();

            _started = false;
        }
Exemple #14
0
        private static void TestReceivePackets(int numPacketsToSend, int numPacketsToWait, int numPacketsToBreakLoop, double secondsToWait, int packetSize,
                                               PacketCommunicatorReceiveResult expectedResult, int expectedNumPackets,
                                               double expectedMinSeconds, double expectedMaxSeconds)
        {
            string testDescription = "NumPacketsToSend=" + numPacketsToSend + ". NumPacketsToWait=" + numPacketsToWait +
                                     ". NumPacketsToBreakLoop=" + numPacketsToBreakLoop + ". SecondsToWait=" +
                                     secondsToWait + ". PacketSize=" + packetSize;


            const string SourceMac      = "11:22:33:44:55:66";
            const string DestinationMac = "77:88:99:AA:BB:CC";

            using (PacketCommunicator communicator = OpenLiveDevice())
            {
                communicator.SetFilter("ether src " + SourceMac + " and ether dst " + DestinationMac);

                Packet sentPacket = _random.NextEthernetPacket(packetSize, SourceMac, DestinationMac);

                PacketCommunicatorReceiveResult result = PacketCommunicatorReceiveResult.None;

                for (int i = 0; i != numPacketsToSend; ++i)
                {
                    communicator.SendPacket(sentPacket);
                }

                PacketHandler handler = new PacketHandler(sentPacket, communicator, numPacketsToBreakLoop);

                Thread thread = new Thread(delegate()
                {
                    if (numPacketsToBreakLoop == 0)
                    {
                        communicator.Break();
                    }
                    result = communicator.ReceivePackets(numPacketsToWait, handler.Handle);
                });

                DateTime startWaiting = DateTime.Now;
                thread.Start();

                if (!thread.Join(TimeSpan.FromSeconds(secondsToWait)))
                {
                    thread.Abort();
                }
                DateTime finishedWaiting = DateTime.Now;

                Assert.AreEqual(expectedResult, result, testDescription);
                Assert.AreEqual(expectedNumPackets, handler.NumPacketsHandled);
                MoreAssert.IsInRange(expectedMinSeconds, expectedMaxSeconds, (finishedWaiting - startWaiting).TotalSeconds);
            }
        }
Exemple #15
0
        private void PrintPacketInfo(Packet packet)
        {
            IpV4Datagram ip  = packet.Ethernet.IpV4;
            UdpDatagram  udp = ip.Udp;

            if (!ip.Destination.ToString().Contains("192"))
            {
                string server = ip.Destination + ":" + udp.DestinationPort;
                ConsoleMsg.Write($"Connected to game server : {server}", ConsoleMsg.Type.Info, true);
                if (!String.IsNullOrEmpty(Constants.DiscordWebHook))
                {
                    Webhook.SendMessage(PlayerName, server);
                }
                pm.Break();
            }
        }
Exemple #16
0
        private static void TestReceiveSomePackets(int numPacketsToSend, int numPacketsToGet, int numPacketsToBreakLoop, int packetSize, bool nonBlocking,
                                                   PacketCommunicatorReceiveResult expectedResult, int expectedNumPackets, double expectedMinSeconds, double expectedMaxSeconds)
        {
            string testDescription = "NumPacketsToSend=" + numPacketsToSend + ". NumPacketsToGet=" + numPacketsToGet +
                                     ". NumPacketsToBreakLoop=" + numPacketsToBreakLoop + ". PacketSize=" + packetSize +
                                     ". NonBlocking=" + nonBlocking;

            const string SourceMac      = "11:22:33:44:55:66";
            const string DestinationMac = "77:88:99:AA:BB:CC";

            Packet packetToSend = _random.NextEthernetPacket(packetSize, SourceMac, DestinationMac);

            using (PacketCommunicator communicator = OpenLiveDevice())
            {
                communicator.NonBlocking = nonBlocking;
                Assert.AreEqual(nonBlocking, communicator.NonBlocking);
                communicator.SetFilter("ether src " + SourceMac + " and ether dst " + DestinationMac);

                int numPacketsGot;
                for (int i = 0; i != numPacketsToSend; ++i)
                {
                    communicator.SendPacket(packetToSend);
                }

                if (numPacketsToBreakLoop == 0)
                {
                    communicator.Break();
                }

                PacketHandler handler                  = new PacketHandler(packetToSend, communicator, numPacketsToBreakLoop);
                DateTime      startWaiting             = DateTime.Now;
                PacketCommunicatorReceiveResult result = communicator.ReceiveSomePackets(out numPacketsGot, numPacketsToGet,
                                                                                         handler.Handle);
                DateTime finishedWaiting = DateTime.Now;

                Assert.AreEqual(expectedResult, result);
                Assert.AreEqual(expectedNumPackets, numPacketsGot, "NumPacketsGot. Test: " + testDescription);
                Assert.AreEqual(expectedNumPackets, handler.NumPacketsHandled, "NumPacketsHandled. Test: " + testDescription);
                MoreAssert.IsInRange(expectedMinSeconds, expectedMaxSeconds, (finishedWaiting - startWaiting).TotalSeconds, testDescription);
            }
        }
Exemple #17
0
        private static void TestReceivePackets(int numPacketsToSend, int numPacketsToGet, int numPacketsToBreakLoop,
                                               PacketCommunicatorReceiveResult expectedResult, int expectedNumPackets,
                                               double expectedMinSeconds, double expectedMaxSeconds)
        {
            string testDescription = "NumPacketsToSend=" + numPacketsToSend + ". NumPacketsToGet=" + numPacketsToGet +
                                     ". NumPacketsToBreakLoop=" + numPacketsToBreakLoop;

            const string SourceMac      = "11:22:33:44:55:66";
            const string DestinationMac = "77:88:99:AA:BB:CC";

            Packet expectedPacket = _random.NextEthernetPacket(24, SourceMac, DestinationMac);

            using (PacketCommunicator communicator = OpenOfflineDevice(numPacketsToSend, expectedPacket))
            {
                communicator.SetFilter("ether src " + SourceMac + " and ether dst " + DestinationMac);

                if (numPacketsToBreakLoop == 0)
                {
                    communicator.Break();
                }
                PacketHandler handler = new PacketHandler(expectedPacket, expectedMinSeconds, expectedMaxSeconds, communicator, numPacketsToBreakLoop);

                PacketCommunicatorReceiveResult result = PacketCommunicatorReceiveResult.None;
                Thread thread = new Thread(delegate()
                {
                    result = communicator.ReceivePackets(numPacketsToGet, handler.Handle);
                });
                thread.Start();

                if (!thread.Join(TimeSpan.FromSeconds(5)))
                {
                    thread.Abort();
                }

                Assert.AreEqual(expectedResult, result, testDescription);
                Assert.AreEqual(expectedNumPackets, handler.NumPacketsHandled);
            }
        }
Exemple #18
0
        public void Execute(PacketCommunicator packetCommunicator)
        {
            MacAddress?requestedMacAddress = null;

            var timer = new System.Timers.Timer();

            timer.Interval  = 1000;
            timer.AutoReset = true;
            timer.Elapsed  += (sender, eventArgs) => packetCommunicator.SendPacket(PacketBuilder.Build(DateTime.Now));
            timer.Start();

            packetCommunicator.ReceivePackets(-1, packet =>
            {
                if (packet.Ethernet.EtherType == EthernetType.Arp &&
                    packet.Ethernet.Arp.IsValid &&
                    packet.Ethernet.Arp.Operation == ArpOperation.Reply &&
                    packet.Ethernet.Arp.SenderProtocolIpV4Address == IpV4AddressToIdentify)
                {
                    timer.Stop();

                    requestedMacAddress = new MacAddress(
                        packet.Ethernet.Arp.SenderHardwareAddress.ToArray().ReadUInt48(0, Endianity.Big)
                        );

                    packetCommunicator.Break();
                }
            });


            // TODO: What if it never arrives?
            while (requestedMacAddress == null)
            {
                ;
            }

            OnIdentified(requestedMacAddress.Value);
        }
            //public Packet CreateDhcpPacket(int optionsSize, byte[] options, bool firstPacket, byte[] clientIp = null)
            //{
            //    EthernetLayer ethernetLayer = new EthernetLayer
            //    {
            //        Source = ifHardwareAddress,
            //        Destination = new MacAddress("FF:FF:FF:FF:FF:FF"),
            //        EtherType = EthernetType.None,
            //    };

            //    IpV4Layer ipV4Layer = new IpV4Layer
            //    {
            //        Source = new IpV4Address("0.0.0.0"),
            //        CurrentDestination = new IpV4Address("255.255.255.255"),
            //        Fragmentation = IpV4Fragmentation.None,
            //        HeaderChecksum = null, // Will be filled automatically.
            //        Identification = ipID,
            //        Options = IpV4Options.None,
            //        Protocol = null,
            //        Ttl = 128,
            //        TypeOfService = 0,
            //    };

            //    UdpLayer udpLayer = new UdpLayer
            //    {
            //        SourcePort = 68,
            //        DestinationPort = 67,
            //        Checksum = null, // Will be filled automatically.
            //        CalculateChecksumValue = true,
            //    };

            //    Dhcp dhcpLayer = new Dhcp(optionsSize);
            //    if (firstPacket)
            //        dhcpId = dhcpLayer.Id;
            //    else
            //        dhcpLayer.Id = dhcpId;
            //    if (clientIp != null)
            //        dhcpLayer.ClientIp = clientIp;
            //    dhcpLayer.ClientHardwareAddress = ifHardwareAddressByte;
            //    dhcpLayer.Options = options;


            //    PayloadLayer payloadLayer = new PayloadLayer
            //    {
            //        Data = new Datagram(dhcpLayer.toByteArray()),
            //    };

            //    PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, udpLayer, payloadLayer);
            //    return builder.Build(DateTime.Now);
            //}
            //public void SendArp()
            //{
            //    EthernetLayer ethernetLayer = new EthernetLayer
            //    {
            //        Source = ifHardwareAddress,
            //        Destination = new MacAddress("FF:FF:FF:FF:FF:FF"),
            //        EtherType = EthernetType.None,
            //    };

            //    ArpLayer arpLayer = new ArpLayer
            //    {
            //        ProtocolType = EthernetType.IpV4,
            //        Operation = ArpOperation.Request,
            //        SenderHardwareAddress = ifHardwareAddressByte.AsReadOnly(),
            //        SenderProtocolAddress = ownProtocolAddressByte.AsReadOnly(),
            //        TargetHardwareAddress = new byte[] { 0, 0, 0, 0, 0, 0 }.AsReadOnly(),
            //        TargetProtocolAddress = gatewayProtocolAddressByte.AsReadOnly(),
            //    };

            //    PacketBuilder builder = new PacketBuilder(ethernetLayer, arpLayer);
            //    SendPacket(builder.Build(DateTime.Now));
            //}
            //public void ReceiveIpAddress()
            //{
            //    int retries = 0;
            //    int timewait = 0;
            //    dhcpState = 0;
            //    arpState = 0;

            //    byte[] options;
            //    while (true)
            //    {
            //        if (dhcpState == 1 && retries > 1 ||
            //            dhcpState == 3 && retries > 1)
            //        {
            //            dhcpState = 6;
            //            offeredIp = BitConverter.GetBytes(ifProtocolAddress.ToValue() & ifProtocolMask.ToValue() + 1).Reverse().ToArray();
            //        }
            //        if (dhcpState == 0 || dhcpState == 1 && timewait > 10)
            //        {
            //            options = new byte[]
            //        { 
            //            53, 1, 1,
            //            61, 7, 1, 0x0A, 0x03, 0x03, 0x03, 0x03, (byte)dhcpClientId,
            //            12, 4, 78, 77, 76, 66,
            //            60, 8, 0x4d, 0x53, 0x46, 0x54, 0x20, 0x35, 0x2e, 0x30,
            //            255,
            //            0, 0, 0,
            //        };
            //            SendPacket(CreateDhcpPacket(32, options, true));
            //            if (dhcpState == 0)
            //                retries = 0;
            //            else
            //                retries++;
            //            timewait = 0;
            //            dhcpState = 1;
            //        }
            //        else if (dhcpState == 2 || dhcpState == 3 && timewait > 10)
            //        {
            //            options = new byte[]
            //        { 
            //            53, 1, 3,
            //            61, 7, 1, 0x0A, 0x03, 0x03, 0x03, 0x03, (byte)dhcpClientId,
            //            12, 4, 78, 77, 76, 66,
            //            50, 4, offeredIp[0], offeredIp[1], offeredIp[2], offeredIp[3],
            //            54, 4, dhcpServer[0], dhcpServer[1], dhcpServer[2], dhcpServer[3],
            //            60, 8, 0x4d, 0x53, 0x46, 0x54, 0x20, 0x35, 0x2e, 0x30,
            //            255,
            //            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            //        };
            //            SendPacket(CreateDhcpPacket(60, options, false));
            //            if (dhcpState == 2)
            //                retries = 0;
            //            else
            //                retries++;
            //            timewait = 0;
            //            dhcpState = 3;
            //        }
            //        else if (dhcpState == 4 && arpState == 1 && retries > 1)
            //        {
            //            if ((BitConverter.ToUInt32(offeredIp.Reverse().ToArray(), 0) + 1 & ifProtocolMask.ToValue()) !=
            //                (ifProtocolAddress.ToValue() & ifProtocolMask.ToValue()))
            //            {
            //                Global.WriteLog("DHCP: IP " + offeredIp.SequenceToString(".") + " is in a different network!");
            //                offeredIp = BitConverter.GetBytes(ifProtocolAddress.ToValue() & ifProtocolMask.ToValue() + 1).Reverse().ToArray();
            //                dhcpState = 6;
            //                arpState = 0;
            //                continue;
            //            }
            //            dhcpState = 5;
            //            arpState = 0;
            //            Global.WriteLog("DHCP: IP " + offeredIp.SequenceToString(".") + " OK!");
            //            dhcpClientId++;
            //            ownProtocolAddressByte = offeredIp;
            //            ownProtocolAddressString = ownProtocolAddressByte.SequenceToString(".");
            //            ownProtocolAddress = new IpV4Address(ownProtocolAddressString);
            //            SendArp();
            //            break;
            //        }
            //        else if (dhcpState == 4 && arpState == 0 || dhcpState == 4 && arpState == 1 && timewait > 10)
            //        {
            //            EthernetLayer ethernetLayer = new EthernetLayer
            //            {
            //                Source = ifHardwareAddress,
            //                Destination = new MacAddress("FF:FF:FF:FF:FF:FF"),
            //                EtherType = EthernetType.None,
            //            };

            //            ArpLayer arpLayer = new ArpLayer
            //            {
            //                ProtocolType = EthernetType.IpV4,
            //                Operation = ArpOperation.Request,
            //                SenderHardwareAddress = ifHardwareAddressByte.AsReadOnly(),
            //                SenderProtocolAddress = new byte[] { 0, 0, 0, 0 }.AsReadOnly(),
            //                TargetHardwareAddress = new byte[] { 0, 0, 0, 0, 0, 0 }.AsReadOnly(),
            //                TargetProtocolAddress = offeredIp.AsReadOnly(),
            //            };

            //            PacketBuilder builder = new PacketBuilder(ethernetLayer, arpLayer);
            //            SendPacket(builder.Build(DateTime.Now));
            //            if (arpState == 0)
            //                retries = 0;
            //            else
            //                retries++;
            //            timewait = 0;
            //            arpState = 1;
            //        }
            //        else if (dhcpState == 4 && arpState == 2)
            //        {
            //            Global.WriteLog("DHCP: IP " + offeredIp.SequenceToString(".") + " is already used!");
            //            options = new byte[]
            //        { 
            //            53, 1, 4,
            //            61, 7, 1, 0x0A, 0x03, 0x03, 0x03, 0x03, (byte)dhcpClientId,
            //            50, 4, offeredIp[0], offeredIp[1], offeredIp[2], offeredIp[3],
            //            54, 4, dhcpServer[0], dhcpServer[1], dhcpServer[2], dhcpServer[3],
            //            255,
            //            //0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
            //        };
            //            SendPacket(CreateDhcpPacket(25, options, false, offeredIp));
            //            arpState = 0;
            //            dhcpState = 0;
            //        }
            //        else if (dhcpState == 6 && arpState == 1 && retries > 1)
            //        {
            //            dhcpState = 5;
            //            arpState = 0;
            //            Global.WriteLog("IPAlloc: IP " + offeredIp.SequenceToString(".") + " OK!");
            //            dhcpClientId++;
            //            ownProtocolAddressByte = offeredIp;
            //            ownProtocolAddressString = ownProtocolAddressByte.SequenceToString(".");
            //            ownProtocolAddress = new IpV4Address(ownProtocolAddressString);
            //            SendArp();
            //            break;
            //        }
            //        else if (dhcpState == 6 && arpState == 0 || dhcpState == 6 && arpState == 1 && timewait > 10)
            //        {
            //            EthernetLayer ethernetLayer = new EthernetLayer
            //            {
            //                Source = ifHardwareAddress,
            //                Destination = new MacAddress("FF:FF:FF:FF:FF:FF"),
            //                EtherType = EthernetType.None,
            //            };

            //            ArpLayer arpLayer = new ArpLayer
            //            {
            //                ProtocolType = EthernetType.IpV4,
            //                Operation = ArpOperation.Request,
            //                SenderHardwareAddress = ifHardwareAddressByte.AsReadOnly(),
            //                SenderProtocolAddress = new byte[] { 0, 0, 0, 0 }.AsReadOnly(),
            //                TargetHardwareAddress = new byte[] { 0, 0, 0, 0, 0, 0 }.AsReadOnly(),
            //                TargetProtocolAddress = offeredIp.AsReadOnly(),
            //            };

            //            PacketBuilder builder = new PacketBuilder(ethernetLayer, arpLayer);
            //            SendPacket(builder.Build(DateTime.Now));
            //            if (arpState == 0)
            //                retries = 0;
            //            else
            //                retries++;
            //            timewait = 0;
            //            arpState = 1;
            //        }
            //        else if (dhcpState == 6 && arpState == 2)
            //        {
            //            if ((BitConverter.ToUInt32(offeredIp.Reverse().ToArray(), 0) + 1 & ifProtocolMask.ToValue()) !=
            //                (ifProtocolAddress.ToValue() & ifProtocolMask.ToValue()))
            //            {
            //                Global.WriteLog("IPAlloc: Couldn't allocate IP address!");
            //                break;
            //            }
            //            Global.WriteLog("IPAlloc: IP " + offeredIp.SequenceToString(".") + " is already used!");
            //            offeredIp = BitConverter.GetBytes((BitConverter.ToUInt32(offeredIp.Reverse().ToArray(), 0) + 1)).Reverse().ToArray();
            //            arpState = 0;
            //        }
            //        Thread.Sleep(100);
            //        timewait++;
            //    }
            //}

            public void ReceivePackets()
            {
                // Retrieve the device list from the local machine
                IList<LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine;

                // Find the NPF device of the interface
                PacketDevice selectedDevice = null;
                for (int i = 0; i != allDevices.Count; ++i)
                {
                    LivePacketDevice device = allDevices[i];
                    if (device.Name.ToUpper().Contains(Guid.ToString().ToUpper()))
                    {
                        selectedDevice = device;
                        break;
                    }
                }

                if (selectedDevice == null)
                {
                    Initialized.Set();
                    Global.ShowTrayTip("Load Balancer", "Interface " + Name + " not captured by WinPcap.", System.Windows.Forms.ToolTipIcon.Warning);
                    Global.WriteLog("Load Balancer: Interface " + Name + " not captured by WinPcap.");
                    return;
                }

                try
                {
                    using (communicator = selectedDevice.Open(65536, PacketDeviceOpenAttributes.MaximumResponsiveness, 1000))
                    {
                        Global.WriteLog("Load Balancer: Listening on " + Name + "...");
                        //communicator.SetFilter("(ether dst " + ifHardwareAddressString + " and (ip or arp)) or (ether dst FF:FF:FF:FF:FF:FF and arp)");
                        communicator.SetFilter("(ether dst " + ifHardwareAddressString + " and ip and (udp or icmp))");
                        Initialized.Set();
                        communicator.ReceivePackets(0, (packet) =>
                        {
                            if (!ThreadActive.IsSet)
                            {
                                communicator.Break();
                                return;
                            }
                            //if (ownProtocolAddressString == null)
                            //{
                            //    if (packet.Ethernet.IpV4.Udp.SourcePort == 67 && packet.Ethernet.IpV4.Udp.DestinationPort == 68 && (PublicVars.dhcpState == 1 || PublicVars.dhcpState == 3))
                            //    {
                            //        Dhcp dhcpReply = new Dhcp(packet.Ethernet.IpV4.Udp.Payload.ToArray());
                            //        if (PublicVars.dhcpId == dhcpReply.Id && dhcpReply.MessageType == 2)
                            //        {
                            //            if (dhcpReply.getOption((int)DhcpOptionCode.DhcpMsgType)[0] == 2)
                            //            {
                            //                PublicVars.offeredIp = dhcpReply.YourIp;
                            //                PublicVars.dhcpServer = dhcpReply.getOption((int)DhcpOptionCode.DhcpServerId);
                            //                PublicVars.dhcpState = 2;
                            //            }
                            //            else if (dhcpReply.getOption((int)DhcpOptionCode.DhcpMsgType)[0] == 5)
                            //            {
                            //                PublicVars.dhcpState = 4;
                            //            }
                            //            else if (dhcpReply.getOption((int)DhcpOptionCode.DhcpMsgType)[0] == 6)
                            //            {
                            //                PublicVars.offeredIp = null;
                            //                PublicVars.dhcpState = 0;
                            //                PublicVars.dhcpId = 0;
                            //            }
                            //        }
                            //    }
                            //    else if (packet.Ethernet.EtherType == EthernetType.Arp && PublicVars.arpState == 1)
                            //    {
                            //        if (packet.Ethernet.Arp.SenderProtocolAddress.SequenceEqual(PublicVars.offeredIp))
                            //            PublicVars.arpState = 2;
                            //    }
                            //}
                            //if (packet.Ethernet.EtherType == EthernetType.Arp)
                            //{
                            //    if (packet.Ethernet.Arp.TargetProtocolAddress.SequenceEqual(ownProtocolAddressByte) &&
                            //        packet.Ethernet.Arp.Operation == ArpOperation.Request)
                            //    {
                            //        EthernetLayer ethernetLayer = new EthernetLayer
                            //        {
                            //            Source = ifHardwareAddress,
                            //            Destination = packet.Ethernet.Source,
                            //            EtherType = EthernetType.None,
                            //        };

                            //        ArpLayer arpLayer = new ArpLayer
                            //        {
                            //            ProtocolType = EthernetType.IpV4,
                            //            Operation = ArpOperation.Reply,
                            //            SenderHardwareAddress = ifHardwareAddressByte.AsReadOnly(),
                            //            SenderProtocolAddress = packet.Ethernet.Arp.TargetProtocolAddress,
                            //            TargetHardwareAddress = packet.Ethernet.Arp.SenderHardwareAddress,
                            //            TargetProtocolAddress = packet.Ethernet.Arp.SenderProtocolAddress,
                            //        };

                            //        PacketBuilder builder = new PacketBuilder(ethernetLayer, arpLayer);
                            //        communicator.SendPacket(builder.Build(DateTime.Now));
                            //    }
                            //}
                            if (tapWorker.Initialized.IsSet)
                            {
                                if (packet.Ethernet.IpV4.Length > MTU) // only UDP and ICMP
                                {
                                    EthernetLayer ethernetLayer = new EthernetLayer
                                    {
                                        Source = ifHardwareAddress,
                                        Destination = packet.Ethernet.Source,
                                        EtherType = EthernetType.None,
                                    };
                                    IpV4Layer ipV4Layer = new IpV4Layer
                                    {
                                        Source = packet.Ethernet.IpV4.Destination,
                                        CurrentDestination = packet.Ethernet.IpV4.Source,
                                        Fragmentation = packet.Ethernet.IpV4.Fragmentation,
                                        HeaderChecksum = null, // Will be filled automatically.
                                        Identification = 123,
                                        Options = packet.Ethernet.IpV4.Options,
                                        Protocol = packet.Ethernet.IpV4.Protocol,
                                        Ttl = packet.Ethernet.IpV4.Ttl,
                                        TypeOfService = packet.Ethernet.IpV4.TypeOfService,
                                    };
                                    IcmpDestinationUnreachableLayer icmpLayer = new IcmpDestinationUnreachableLayer
                                    {
                                        Code = IcmpCodeDestinationUnreachable.FragmentationNeededAndDoNotFragmentSet,
                                        NextHopMaximumTransmissionUnit = (ushort)MTU,
                                    };

                                    PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, icmpLayer);
                                    SendPacket(builder.Build(DateTime.Now));
                                    // TODO: fix warning spam
                                    if (Global.Config.LoadBalancer.ShowTrayTipsWarnings)
                                        Global.ShowTrayTip("Load Balancer", "IP packet larger than the MTU detected on " + Name + ".\n\nIP fragmentation is not supported.", ToolTipIcon.Warning);
                                    Global.WriteLog("Load Balancer: IP packet larger than the MTU detected on " + Name);
                                    return;
                                }
                                if (packet.Ethernet.IpV4.Fragmentation.Options == IpV4FragmentationOptions.DoNotFragment ||
                                packet.Ethernet.IpV4.Fragmentation.Options == IpV4FragmentationOptions.None && packet.Ethernet.IpV4.Fragmentation.Offset == 0)
                                {
                                    if (packet.Ethernet.IpV4.Protocol == IpV4Protocol.InternetControlMessageProtocol)
                                    {

                                        if (packet.Ethernet.IpV4.Destination == ifProtocolAddress)
                                            if ((packet.Ethernet.IpV4.Icmp.MessageType == IcmpMessageType.EchoReply || packet.Ethernet.IpV4.Fragmentation.Offset > 0))
                                            {
                                                EthernetLayer ethernetLayer = new EthernetLayer
                                                {
                                                    Source = tapWorker.ownHardwareAddress,
                                                    Destination = tapWorker.ifHardwareAddress,
                                                    EtherType = EthernetType.None,
                                                };
                                                IpV4Layer ipV4Layer = new IpV4Layer
                                                {
                                                    Source = packet.Ethernet.IpV4.Source,
                                                    CurrentDestination = tapWorker.ifProtocolAddress,
                                                    Fragmentation = packet.Ethernet.IpV4.Fragmentation,
                                                    HeaderChecksum = null, // Will be filled automatically.
                                                    Identification = packet.Ethernet.IpV4.Identification,
                                                    Options = packet.Ethernet.IpV4.Options,
                                                    Protocol = packet.Ethernet.IpV4.Protocol,
                                                    Ttl = packet.Ethernet.IpV4.Ttl,
                                                    TypeOfService = packet.Ethernet.IpV4.TypeOfService,
                                                };
                                                PayloadLayer payloadLayer = new PayloadLayer
                                                {
                                                    Data = new Datagram(packet.Ethernet.IpV4.Payload.ToArray()),
                                                };
                                                PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, payloadLayer);
                                                tapWorker.SendPacket(builder.Build(DateTime.Now));
                                            }
                                    }
                                    //else if (packet.Ethernet.IpV4.Protocol == IpV4Protocol.Tcp)
                                    //{
                                    //    if (packet.Ethernet.IpV4.Destination == ifProtocolAddress)
                                    //    {
                                    //        lock (RoutingTable.lockObj)
                                    //            routingObject = RoutingTable.TranslateBack(packet);
                                    //        if (routingObject.ifIndex == -1)
                                    //            return;
                                    //        EthernetLayer ethernetLayer = new EthernetLayer
                                    //        {
                                    //            Source = TapWorker.ownHardwareAddress,
                                    //            Destination = TapWorker.ifHardwareAddress,
                                    //            EtherType = packet.Ethernet.EtherType,
                                    //        };
                                    //        IpV4Layer ipV4Layer = new IpV4Layer
                                    //        {
                                    //            Source = packet.Ethernet.IpV4.Source,
                                    //            CurrentDestination = TapWorker.ifProtocolAddress,
                                    //            Fragmentation = packet.Ethernet.IpV4.Fragmentation,
                                    //            HeaderChecksum = null, // Will be filled automatically.
                                    //            Identification = packet.Ethernet.IpV4.Identification,
                                    //            Options = packet.Ethernet.IpV4.Options,
                                    //            Protocol = packet.Ethernet.IpV4.Protocol,
                                    //            Ttl = packet.Ethernet.IpV4.Ttl,
                                    //            TypeOfService = packet.Ethernet.IpV4.TypeOfService,
                                    //        };
                                    //        TcpLayer tcpLayer = new TcpLayer
                                    //        {
                                    //            SourcePort = packet.Ethernet.IpV4.Tcp.SourcePort,
                                    //            DestinationPort = routingObject.localPort,
                                    //            Checksum = null, // Will be filled automatically.
                                    //            SequenceNumber = packet.Ethernet.IpV4.Tcp.SequenceNumber,
                                    //            AcknowledgmentNumber = routingObject.ack,
                                    //            ControlBits = packet.Ethernet.IpV4.Tcp.ControlBits,
                                    //            Window = packet.Ethernet.IpV4.Tcp.Window,
                                    //            UrgentPointer = packet.Ethernet.IpV4.Tcp.UrgentPointer,
                                    //            Options = packet.Ethernet.IpV4.Tcp.Options,
                                    //        };
                                    //        PayloadLayer payloadLayer = new PayloadLayer
                                    //        {
                                    //            Data = new Datagram(packet.Ethernet.IpV4.Tcp.Payload.ToArray()),
                                    //        };
                                    //        PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, tcpLayer, payloadLayer);
                                    //        MainThread.tapWorker.SendPacket(builder.Build(DateTime.Now));
                                    //    }
                                    //}
                                    else if (packet.Ethernet.IpV4.Protocol == IpV4Protocol.Udp)
                                    {
                                        if (packet.Ethernet.IpV4.Destination == ifProtocolAddress)
                                        {
                                            phyRoutingObject = RoutingTable.IsUdpConn(packet);
                                            if (phyRoutingObject.ifIndex == -1)
                                                return;
                                            EthernetLayer ethernetLayer = new EthernetLayer
                                            {
                                                Source = tapWorker.ownHardwareAddress,
                                                Destination = tapWorker.ifHardwareAddress,
                                                EtherType = packet.Ethernet.EtherType,
                                            };
                                            IpV4Layer ipV4Layer = new IpV4Layer
                                            {
                                                Source = packet.Ethernet.IpV4.Source,
                                                CurrentDestination = tapWorker.ifProtocolAddress,
                                                Fragmentation = packet.Ethernet.IpV4.Fragmentation,
                                                HeaderChecksum = null, // Will be filled automatically.
                                                Identification = packet.Ethernet.IpV4.Identification,
                                                Options = packet.Ethernet.IpV4.Options,
                                                Protocol = packet.Ethernet.IpV4.Protocol,
                                                Ttl = packet.Ethernet.IpV4.Ttl,
                                                TypeOfService = packet.Ethernet.IpV4.TypeOfService,
                                            };
                                            UdpLayer udpLayer = new UdpLayer
                                            {
                                                SourcePort = packet.Ethernet.IpV4.Udp.SourcePort,
                                                DestinationPort = packet.Ethernet.IpV4.Udp.DestinationPort,
                                                Checksum = null, // Will be filled automatically.
                                                CalculateChecksumValue = packet.Ethernet.IpV4.Udp.IsChecksumOptional,
                                            };
                                            PayloadLayer payloadLayer = new PayloadLayer
                                            {
                                                Data = new Datagram(packet.Ethernet.IpV4.Udp.Payload.ToArray()),
                                            };
                                            PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, udpLayer, payloadLayer);
                                            tapWorker.SendPacket(builder.Build(DateTime.Now));
                                        }
                                    }
                                }
                                else if (packet.Ethernet.IpV4.Fragmentation.Options == IpV4FragmentationOptions.MoreFragments ||
                                    packet.Ethernet.IpV4.Fragmentation.Options == IpV4FragmentationOptions.None && packet.Ethernet.IpV4.Fragmentation.Offset > 0)
                                {
                                    // TODO: fix warning spam
                                    if (Global.Config.LoadBalancer.ShowTrayTipsWarnings)
                                        Global.ShowTrayTip("Load Balancer", "IP fragmentation detected on " + Name + ".\n\nIP fragmentation is not supported.", ToolTipIcon.Warning);
                                    Global.WriteLog("Load Balancer: IP fragmentation detected on " + Name);
                                    //fragments = fragBuffer.Add(packet);
                                    //if (fragments != null)
                                    //    for (int i = 0; i < fragments.Count; i++)
                                    //    {
                                    //        IpV4Handler(fragments[i], fragments);
                                    //    }
                                }
                            }
                        });
                    }
                }
                catch (Exception e)
                {
                    if (ThreadActive.IsSet)
                    {
                        ThreadActive.Reset();
                        Global.WriteLog("Load Balancer: " + Name + " has disconnected");
                        if (Global.Config.Gadget.Debug)
                            Global.WriteLog(e.ToString());
                        Global.ShowTrayTip("Load Balancer", Name + " has disconnected", System.Windows.Forms.ToolTipIcon.Warning);
                    }
                }
            }
 public void StopCapturing()
 {
     //stopSignal = true;
     _communicator.Break();
     FireStatusChanged("Listening stopped.");
 }
Exemple #21
0
        public static MacAddress?GetMacByIpAddress(LivePacketDevice iface, PacketCommunicator communicator, IpV4Address sourceAddress, IpV4Address targetAddress, int timeout = 2000)
        {
            var sourcePhysicalAddress = iface.GetNetworkInterface().GetPhysicalAddress();

            MacAddress?result     = null;
            var        resultLock = new object();

            var tokenSource       = new CancellationTokenSource();
            var cancellationToken = tokenSource.Token;

            var packet = PacketBuilder.Build(
                DateTime.Now,
                new EthernetLayer()
            {
                EtherType   = EthernetType.None,
                Source      = PhysicalAddressToMacAddress(sourcePhysicalAddress),
                Destination = BroadcastMac,
            },
                new ArpLayer()
            {
                ProtocolType          = EthernetType.IpV4,
                Operation             = ArpOperation.Request,
                SenderProtocolAddress = sourceAddress.ToBytes(),
                SenderHardwareAddress = sourcePhysicalAddress.GetAddressBytes().AsReadOnly(),
                TargetProtocolAddress = targetAddress.ToBytes(),
                TargetHardwareAddress = MacAddress.Zero.ToBytes(),
            }
                );

            communicator.SendPacket(packet);

            Task.Run(() =>
            {
                while (true)
                {
                    if (cancellationToken.IsCancellationRequested)
                    {
                        break;
                    }

                    communicator.ReceivePacket(out Packet p);

                    if (p != null &&
                        p.IsValid &&
                        p.Ethernet.IsValid &&
                        p.Ethernet.EtherType == EthernetType.Arp &&
                        p.Ethernet.Arp.IsValid &&
                        p.Ethernet.Arp.Operation == ArpOperation.Reply &&
                        p.Ethernet.Arp.SenderProtocolIpV4Address == targetAddress &&
                        p.Ethernet.Arp.TargetProtocolIpV4Address == sourceAddress)
                    {
                        lock (resultLock)
                            result = new MacAddress(BitConverter.ToString(p.Ethernet.Arp.SenderHardwareAddress.ToArray()).Replace('-', ':'));

                        break;
                    }
                }
            });

            var stopwatch = new Stopwatch();

            stopwatch.Start();

            while (true)
            {
                lock (resultLock)
                {
                    if (result != null)
                    {
                        return(result);
                    }
                }

                if (stopwatch.ElapsedMilliseconds >= timeout)
                {
                    tokenSource.Cancel();
                    communicator.Break();
                    break;
                }
                else
                {
                    Thread.Sleep(100);
                }
            }

            return(result);
        }
        public void PacketHandler()
        {
            Packet packet;

            try
            {
                IsBusy = true;
                cts    = new CancellationTokenSource();
                CancellationToken token = cts.Token;

                // Open the device
                communicator = SelectedInterface.Open(65536,                                  // 65536 guarantees that the whole packet will be captured on all the link layers
                                                      PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode
                                                      1000);                                  // read timeout

                if (!string.IsNullOrEmpty(trafficFilter))
                {
                    communicator.SetFilter(trafficFilter);
                }

                do
                {
                    PacketCommunicatorReceiveResult result = communicator.ReceivePacket(out packet);
                    switch (result)
                    {
                    case PacketCommunicatorReceiveResult.Timeout:
                        // Timeout elapsed
                        continue;

                    case PacketCommunicatorReceiveResult.Ok:
                        if (packet.Ethernet.EtherType == EthernetType.IpV4)
                        {
                            Application.Current.Dispatcher.Invoke(() =>
                            {
                                packets.Add(packet);
                                StatHandler.UpdateStats(packet);
                            });
                        }
                        break;

                    default:
                        throw new InvalidOperationException("PacketCommunicator InvalidOperationException");
                    }
                } while (!token.IsCancellationRequested);
            }
            catch (Exception ex)
            {
                MessageBox.Show("A handled exception occurred: " + ex.Message, "Tcp/Ip sniffer",
                                MessageBoxButton.OK, MessageBoxImage.Warning);
            }
            finally
            {
                communicator.Break();
                communicator.Dispose();
                communicator = null;

                cts.Dispose();
                cts    = null;
                IsBusy = false;
            }
        }
Exemple #23
0
            public void ReceivePackets()
            {
                // Retrieve the device list from the local machine
                IList <LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine;

                // Find the NPF device of the TAP interface
                PacketDevice selectedDevice = null;

                for (int i = 0; i != allDevices.Count; ++i)
                {
                    LivePacketDevice device = allDevices[i];
                    if (device.Name.ToUpper().Contains(Guid.ToString().ToUpper()))
                    {
                        selectedDevice = device;
                        break;
                    }
                }

                if (selectedDevice == null)
                {
                    Initialized.Set();
                    Global.ShowTrayTip("Load Balancer", "Interface " + Name + " not captured by WinPcap.", System.Windows.Forms.ToolTipIcon.Warning);
                    Global.WriteLog("Load Balancer: Interface " + Name + " not captured by WinPcap.");
                    return;
                }

                try
                {
                    using (communicator = selectedDevice.Open(65536, PacketDeviceOpenAttributes.MaximumResponsiveness, 1000))
                    {
                        Global.WriteLog("Load Balancer: Listening on " + Name + "...");
                        communicator.SetFilter("(ether dst " + ownHardwareAddressString + " and ((ip and (tcp or udp or icmp)) or arp)) or (ether dst FF:FF:FF:FF:FF:FF and arp)");
                        Initialized.Set();
                        communicator.ReceivePackets(0, (packet) =>
                        {
                            if (!ThreadActive.IsSet)
                            {
                                communicator.Break();
                                return;
                            }
                            if (packet.Ethernet.EtherType == EthernetType.Arp)
                            {
                                if (packet.Ethernet.Arp.TargetProtocolAddress.SequenceEqual(ownProtocolAddressByte) && packet.Ethernet.Arp.Operation == ArpOperation.Request)
                                {
                                    EthernetLayer ethernetLayer = new EthernetLayer
                                    {
                                        Source      = ownHardwareAddress,
                                        Destination = packet.Ethernet.Source,
                                        EtherType   = EthernetType.None,
                                    };

                                    ArpLayer arpLayer = new ArpLayer
                                    {
                                        ProtocolType          = EthernetType.IpV4,
                                        Operation             = ArpOperation.Reply,
                                        SenderHardwareAddress = ownHardwareAddressByte.AsReadOnly(),
                                        SenderProtocolAddress = packet.Ethernet.Arp.TargetProtocolAddress,
                                        TargetHardwareAddress = packet.Ethernet.Arp.SenderHardwareAddress,
                                        TargetProtocolAddress = packet.Ethernet.Arp.SenderProtocolAddress,
                                    };

                                    PacketBuilder builder = new PacketBuilder(ethernetLayer, arpLayer);
                                    SendPacket(builder.Build(DateTime.Now));
                                }
                            }
                            else if (packet.Ethernet.EtherType.ToString() == "IpV4")
                            {
                                if (packet.Ethernet.IpV4.Fragmentation.Options == IpV4FragmentationOptions.DoNotFragment ||
                                    packet.Ethernet.IpV4.Fragmentation.Options == IpV4FragmentationOptions.None && packet.Ethernet.IpV4.Fragmentation.Offset == 0)
                                {
                                    IpV4Handler(packet);
                                }
                                else if (packet.Ethernet.IpV4.Fragmentation.Options == IpV4FragmentationOptions.MoreFragments ||
                                         packet.Ethernet.IpV4.Fragmentation.Options == IpV4FragmentationOptions.None && packet.Ethernet.IpV4.Fragmentation.Offset > 0)
                                {
                                    // TODO: fix warning spam
                                    if (Global.Config.LoadBalancer.ShowTrayTipsWarnings)
                                    {
                                        Global.ShowTrayTip("Load Balancer", "IP fragmentation detected on " + Name + ".\n\nIP fragmentation is not supported.", ToolTipIcon.Warning);
                                    }
                                    Global.WriteLog("Load Balancer: IP fragmentation detected on " + Name);
                                    //fragments = fragBuffer.Add(packet);
                                    //if (fragments != null)
                                    //    for (int i = 0; i < fragments.Count; i++)
                                    //    {
                                    //        IpV4Handler(fragments[i], fragments);
                                    //    }
                                }
                            }
                        });
                    }
                }
                catch (Exception e)
                {
                    if (ThreadActive.IsSet)
                    {
                        ThreadActive.Reset();
                        Global.WriteLog("Load Balancer: " + Name + " has disconnected");
                        if (Global.Config.Gadget.Debug)
                        {
                            Global.WriteLog(e.ToString());
                        }
                        Global.ShowTrayTip("Load Balancer", Name + " has disconnected", System.Windows.Forms.ToolTipIcon.Warning);
                    }
                }
            }
Exemple #24
0
            //public Packet CreateDhcpPacket(int optionsSize, byte[] options, bool firstPacket, byte[] clientIp = null)
            //{
            //    EthernetLayer ethernetLayer = new EthernetLayer
            //    {
            //        Source = ifHardwareAddress,
            //        Destination = new MacAddress("FF:FF:FF:FF:FF:FF"),
            //        EtherType = EthernetType.None,
            //    };

            //    IpV4Layer ipV4Layer = new IpV4Layer
            //    {
            //        Source = new IpV4Address("0.0.0.0"),
            //        CurrentDestination = new IpV4Address("255.255.255.255"),
            //        Fragmentation = IpV4Fragmentation.None,
            //        HeaderChecksum = null, // Will be filled automatically.
            //        Identification = ipID,
            //        Options = IpV4Options.None,
            //        Protocol = null,
            //        Ttl = 128,
            //        TypeOfService = 0,
            //    };

            //    UdpLayer udpLayer = new UdpLayer
            //    {
            //        SourcePort = 68,
            //        DestinationPort = 67,
            //        Checksum = null, // Will be filled automatically.
            //        CalculateChecksumValue = true,
            //    };

            //    Dhcp dhcpLayer = new Dhcp(optionsSize);
            //    if (firstPacket)
            //        dhcpId = dhcpLayer.Id;
            //    else
            //        dhcpLayer.Id = dhcpId;
            //    if (clientIp != null)
            //        dhcpLayer.ClientIp = clientIp;
            //    dhcpLayer.ClientHardwareAddress = ifHardwareAddressByte;
            //    dhcpLayer.Options = options;


            //    PayloadLayer payloadLayer = new PayloadLayer
            //    {
            //        Data = new Datagram(dhcpLayer.toByteArray()),
            //    };

            //    PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, udpLayer, payloadLayer);
            //    return builder.Build(DateTime.Now);
            //}
            //public void SendArp()
            //{
            //    EthernetLayer ethernetLayer = new EthernetLayer
            //    {
            //        Source = ifHardwareAddress,
            //        Destination = new MacAddress("FF:FF:FF:FF:FF:FF"),
            //        EtherType = EthernetType.None,
            //    };

            //    ArpLayer arpLayer = new ArpLayer
            //    {
            //        ProtocolType = EthernetType.IpV4,
            //        Operation = ArpOperation.Request,
            //        SenderHardwareAddress = ifHardwareAddressByte.AsReadOnly(),
            //        SenderProtocolAddress = ownProtocolAddressByte.AsReadOnly(),
            //        TargetHardwareAddress = new byte[] { 0, 0, 0, 0, 0, 0 }.AsReadOnly(),
            //        TargetProtocolAddress = gatewayProtocolAddressByte.AsReadOnly(),
            //    };

            //    PacketBuilder builder = new PacketBuilder(ethernetLayer, arpLayer);
            //    SendPacket(builder.Build(DateTime.Now));
            //}
            //public void ReceiveIpAddress()
            //{
            //    int retries = 0;
            //    int timewait = 0;
            //    dhcpState = 0;
            //    arpState = 0;

            //    byte[] options;
            //    while (true)
            //    {
            //        if (dhcpState == 1 && retries > 1 ||
            //            dhcpState == 3 && retries > 1)
            //        {
            //            dhcpState = 6;
            //            offeredIp = BitConverter.GetBytes(ifProtocolAddress.ToValue() & ifProtocolMask.ToValue() + 1).Reverse().ToArray();
            //        }
            //        if (dhcpState == 0 || dhcpState == 1 && timewait > 10)
            //        {
            //            options = new byte[]
            //        {
            //            53, 1, 1,
            //            61, 7, 1, 0x0A, 0x03, 0x03, 0x03, 0x03, (byte)dhcpClientId,
            //            12, 4, 78, 77, 76, 66,
            //            60, 8, 0x4d, 0x53, 0x46, 0x54, 0x20, 0x35, 0x2e, 0x30,
            //            255,
            //            0, 0, 0,
            //        };
            //            SendPacket(CreateDhcpPacket(32, options, true));
            //            if (dhcpState == 0)
            //                retries = 0;
            //            else
            //                retries++;
            //            timewait = 0;
            //            dhcpState = 1;
            //        }
            //        else if (dhcpState == 2 || dhcpState == 3 && timewait > 10)
            //        {
            //            options = new byte[]
            //        {
            //            53, 1, 3,
            //            61, 7, 1, 0x0A, 0x03, 0x03, 0x03, 0x03, (byte)dhcpClientId,
            //            12, 4, 78, 77, 76, 66,
            //            50, 4, offeredIp[0], offeredIp[1], offeredIp[2], offeredIp[3],
            //            54, 4, dhcpServer[0], dhcpServer[1], dhcpServer[2], dhcpServer[3],
            //            60, 8, 0x4d, 0x53, 0x46, 0x54, 0x20, 0x35, 0x2e, 0x30,
            //            255,
            //            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            //        };
            //            SendPacket(CreateDhcpPacket(60, options, false));
            //            if (dhcpState == 2)
            //                retries = 0;
            //            else
            //                retries++;
            //            timewait = 0;
            //            dhcpState = 3;
            //        }
            //        else if (dhcpState == 4 && arpState == 1 && retries > 1)
            //        {
            //            if ((BitConverter.ToUInt32(offeredIp.Reverse().ToArray(), 0) + 1 & ifProtocolMask.ToValue()) !=
            //                (ifProtocolAddress.ToValue() & ifProtocolMask.ToValue()))
            //            {
            //                Global.WriteLog("DHCP: IP " + offeredIp.SequenceToString(".") + " is in a different network!");
            //                offeredIp = BitConverter.GetBytes(ifProtocolAddress.ToValue() & ifProtocolMask.ToValue() + 1).Reverse().ToArray();
            //                dhcpState = 6;
            //                arpState = 0;
            //                continue;
            //            }
            //            dhcpState = 5;
            //            arpState = 0;
            //            Global.WriteLog("DHCP: IP " + offeredIp.SequenceToString(".") + " OK!");
            //            dhcpClientId++;
            //            ownProtocolAddressByte = offeredIp;
            //            ownProtocolAddressString = ownProtocolAddressByte.SequenceToString(".");
            //            ownProtocolAddress = new IpV4Address(ownProtocolAddressString);
            //            SendArp();
            //            break;
            //        }
            //        else if (dhcpState == 4 && arpState == 0 || dhcpState == 4 && arpState == 1 && timewait > 10)
            //        {
            //            EthernetLayer ethernetLayer = new EthernetLayer
            //            {
            //                Source = ifHardwareAddress,
            //                Destination = new MacAddress("FF:FF:FF:FF:FF:FF"),
            //                EtherType = EthernetType.None,
            //            };

            //            ArpLayer arpLayer = new ArpLayer
            //            {
            //                ProtocolType = EthernetType.IpV4,
            //                Operation = ArpOperation.Request,
            //                SenderHardwareAddress = ifHardwareAddressByte.AsReadOnly(),
            //                SenderProtocolAddress = new byte[] { 0, 0, 0, 0 }.AsReadOnly(),
            //                TargetHardwareAddress = new byte[] { 0, 0, 0, 0, 0, 0 }.AsReadOnly(),
            //                TargetProtocolAddress = offeredIp.AsReadOnly(),
            //            };

            //            PacketBuilder builder = new PacketBuilder(ethernetLayer, arpLayer);
            //            SendPacket(builder.Build(DateTime.Now));
            //            if (arpState == 0)
            //                retries = 0;
            //            else
            //                retries++;
            //            timewait = 0;
            //            arpState = 1;
            //        }
            //        else if (dhcpState == 4 && arpState == 2)
            //        {
            //            Global.WriteLog("DHCP: IP " + offeredIp.SequenceToString(".") + " is already used!");
            //            options = new byte[]
            //        {
            //            53, 1, 4,
            //            61, 7, 1, 0x0A, 0x03, 0x03, 0x03, 0x03, (byte)dhcpClientId,
            //            50, 4, offeredIp[0], offeredIp[1], offeredIp[2], offeredIp[3],
            //            54, 4, dhcpServer[0], dhcpServer[1], dhcpServer[2], dhcpServer[3],
            //            255,
            //            //0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
            //        };
            //            SendPacket(CreateDhcpPacket(25, options, false, offeredIp));
            //            arpState = 0;
            //            dhcpState = 0;
            //        }
            //        else if (dhcpState == 6 && arpState == 1 && retries > 1)
            //        {
            //            dhcpState = 5;
            //            arpState = 0;
            //            Global.WriteLog("IPAlloc: IP " + offeredIp.SequenceToString(".") + " OK!");
            //            dhcpClientId++;
            //            ownProtocolAddressByte = offeredIp;
            //            ownProtocolAddressString = ownProtocolAddressByte.SequenceToString(".");
            //            ownProtocolAddress = new IpV4Address(ownProtocolAddressString);
            //            SendArp();
            //            break;
            //        }
            //        else if (dhcpState == 6 && arpState == 0 || dhcpState == 6 && arpState == 1 && timewait > 10)
            //        {
            //            EthernetLayer ethernetLayer = new EthernetLayer
            //            {
            //                Source = ifHardwareAddress,
            //                Destination = new MacAddress("FF:FF:FF:FF:FF:FF"),
            //                EtherType = EthernetType.None,
            //            };

            //            ArpLayer arpLayer = new ArpLayer
            //            {
            //                ProtocolType = EthernetType.IpV4,
            //                Operation = ArpOperation.Request,
            //                SenderHardwareAddress = ifHardwareAddressByte.AsReadOnly(),
            //                SenderProtocolAddress = new byte[] { 0, 0, 0, 0 }.AsReadOnly(),
            //                TargetHardwareAddress = new byte[] { 0, 0, 0, 0, 0, 0 }.AsReadOnly(),
            //                TargetProtocolAddress = offeredIp.AsReadOnly(),
            //            };

            //            PacketBuilder builder = new PacketBuilder(ethernetLayer, arpLayer);
            //            SendPacket(builder.Build(DateTime.Now));
            //            if (arpState == 0)
            //                retries = 0;
            //            else
            //                retries++;
            //            timewait = 0;
            //            arpState = 1;
            //        }
            //        else if (dhcpState == 6 && arpState == 2)
            //        {
            //            if ((BitConverter.ToUInt32(offeredIp.Reverse().ToArray(), 0) + 1 & ifProtocolMask.ToValue()) !=
            //                (ifProtocolAddress.ToValue() & ifProtocolMask.ToValue()))
            //            {
            //                Global.WriteLog("IPAlloc: Couldn't allocate IP address!");
            //                break;
            //            }
            //            Global.WriteLog("IPAlloc: IP " + offeredIp.SequenceToString(".") + " is already used!");
            //            offeredIp = BitConverter.GetBytes((BitConverter.ToUInt32(offeredIp.Reverse().ToArray(), 0) + 1)).Reverse().ToArray();
            //            arpState = 0;
            //        }
            //        Thread.Sleep(100);
            //        timewait++;
            //    }
            //}

            public void ReceivePackets()
            {
                // Retrieve the device list from the local machine
                IList <LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine;

                // Find the NPF device of the interface
                PacketDevice selectedDevice = null;

                for (int i = 0; i != allDevices.Count; ++i)
                {
                    LivePacketDevice device = allDevices[i];
                    if (device.Name.ToUpper().Contains(Guid.ToString().ToUpper()))
                    {
                        selectedDevice = device;
                        break;
                    }
                }

                if (selectedDevice == null)
                {
                    Initialized.Set();
                    Global.ShowTrayTip("Load Balancer", "Interface " + Name + " not captured by WinPcap.", System.Windows.Forms.ToolTipIcon.Warning);
                    Global.WriteLog("Load Balancer: Interface " + Name + " not captured by WinPcap.");
                    return;
                }

                try
                {
                    using (communicator = selectedDevice.Open(65536, PacketDeviceOpenAttributes.MaximumResponsiveness, 1000))
                    {
                        Global.WriteLog("Load Balancer: Listening on " + Name + "...");
                        //communicator.SetFilter("(ether dst " + ifHardwareAddressString + " and (ip or arp)) or (ether dst FF:FF:FF:FF:FF:FF and arp)");
                        communicator.SetFilter("(ether dst " + ifHardwareAddressString + " and ip and (udp or icmp))");
                        Initialized.Set();
                        communicator.ReceivePackets(0, (packet) =>
                        {
                            if (!ThreadActive.IsSet)
                            {
                                communicator.Break();
                                return;
                            }
                            //if (ownProtocolAddressString == null)
                            //{
                            //    if (packet.Ethernet.IpV4.Udp.SourcePort == 67 && packet.Ethernet.IpV4.Udp.DestinationPort == 68 && (PublicVars.dhcpState == 1 || PublicVars.dhcpState == 3))
                            //    {
                            //        Dhcp dhcpReply = new Dhcp(packet.Ethernet.IpV4.Udp.Payload.ToArray());
                            //        if (PublicVars.dhcpId == dhcpReply.Id && dhcpReply.MessageType == 2)
                            //        {
                            //            if (dhcpReply.getOption((int)DhcpOptionCode.DhcpMsgType)[0] == 2)
                            //            {
                            //                PublicVars.offeredIp = dhcpReply.YourIp;
                            //                PublicVars.dhcpServer = dhcpReply.getOption((int)DhcpOptionCode.DhcpServerId);
                            //                PublicVars.dhcpState = 2;
                            //            }
                            //            else if (dhcpReply.getOption((int)DhcpOptionCode.DhcpMsgType)[0] == 5)
                            //            {
                            //                PublicVars.dhcpState = 4;
                            //            }
                            //            else if (dhcpReply.getOption((int)DhcpOptionCode.DhcpMsgType)[0] == 6)
                            //            {
                            //                PublicVars.offeredIp = null;
                            //                PublicVars.dhcpState = 0;
                            //                PublicVars.dhcpId = 0;
                            //            }
                            //        }
                            //    }
                            //    else if (packet.Ethernet.EtherType == EthernetType.Arp && PublicVars.arpState == 1)
                            //    {
                            //        if (packet.Ethernet.Arp.SenderProtocolAddress.SequenceEqual(PublicVars.offeredIp))
                            //            PublicVars.arpState = 2;
                            //    }
                            //}
                            //if (packet.Ethernet.EtherType == EthernetType.Arp)
                            //{
                            //    if (packet.Ethernet.Arp.TargetProtocolAddress.SequenceEqual(ownProtocolAddressByte) &&
                            //        packet.Ethernet.Arp.Operation == ArpOperation.Request)
                            //    {
                            //        EthernetLayer ethernetLayer = new EthernetLayer
                            //        {
                            //            Source = ifHardwareAddress,
                            //            Destination = packet.Ethernet.Source,
                            //            EtherType = EthernetType.None,
                            //        };

                            //        ArpLayer arpLayer = new ArpLayer
                            //        {
                            //            ProtocolType = EthernetType.IpV4,
                            //            Operation = ArpOperation.Reply,
                            //            SenderHardwareAddress = ifHardwareAddressByte.AsReadOnly(),
                            //            SenderProtocolAddress = packet.Ethernet.Arp.TargetProtocolAddress,
                            //            TargetHardwareAddress = packet.Ethernet.Arp.SenderHardwareAddress,
                            //            TargetProtocolAddress = packet.Ethernet.Arp.SenderProtocolAddress,
                            //        };

                            //        PacketBuilder builder = new PacketBuilder(ethernetLayer, arpLayer);
                            //        communicator.SendPacket(builder.Build(DateTime.Now));
                            //    }
                            //}
                            if (tapWorker.Initialized.IsSet)
                            {
                                if (packet.Ethernet.IpV4.Length > MTU) // only UDP and ICMP
                                {
                                    EthernetLayer ethernetLayer = new EthernetLayer
                                    {
                                        Source      = ifHardwareAddress,
                                        Destination = packet.Ethernet.Source,
                                        EtherType   = EthernetType.None,
                                    };
                                    IpV4Layer ipV4Layer = new IpV4Layer
                                    {
                                        Source             = packet.Ethernet.IpV4.Destination,
                                        CurrentDestination = packet.Ethernet.IpV4.Source,
                                        Fragmentation      = packet.Ethernet.IpV4.Fragmentation,
                                        HeaderChecksum     = null, // Will be filled automatically.
                                        Identification     = 123,
                                        Options            = packet.Ethernet.IpV4.Options,
                                        Protocol           = packet.Ethernet.IpV4.Protocol,
                                        Ttl           = packet.Ethernet.IpV4.Ttl,
                                        TypeOfService = packet.Ethernet.IpV4.TypeOfService,
                                    };
                                    IcmpDestinationUnreachableLayer icmpLayer = new IcmpDestinationUnreachableLayer
                                    {
                                        Code = IcmpCodeDestinationUnreachable.FragmentationNeededAndDoNotFragmentSet,
                                        NextHopMaximumTransmissionUnit = (ushort)MTU,
                                    };

                                    PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, icmpLayer);
                                    SendPacket(builder.Build(DateTime.Now));
                                    // TODO: fix warning spam
                                    if (Global.Config.LoadBalancer.ShowTrayTipsWarnings)
                                    {
                                        Global.ShowTrayTip("Load Balancer", "IP packet larger than the MTU detected on " + Name + ".\n\nIP fragmentation is not supported.", ToolTipIcon.Warning);
                                    }
                                    Global.WriteLog("Load Balancer: IP packet larger than the MTU detected on " + Name);
                                    return;
                                }
                                if (packet.Ethernet.IpV4.Fragmentation.Options == IpV4FragmentationOptions.DoNotFragment ||
                                    packet.Ethernet.IpV4.Fragmentation.Options == IpV4FragmentationOptions.None && packet.Ethernet.IpV4.Fragmentation.Offset == 0)
                                {
                                    if (packet.Ethernet.IpV4.Protocol == IpV4Protocol.InternetControlMessageProtocol)
                                    {
                                        if (packet.Ethernet.IpV4.Destination == ifProtocolAddress)
                                        {
                                            if ((packet.Ethernet.IpV4.Icmp.MessageType == IcmpMessageType.EchoReply || packet.Ethernet.IpV4.Fragmentation.Offset > 0))
                                            {
                                                EthernetLayer ethernetLayer = new EthernetLayer
                                                {
                                                    Source      = tapWorker.ownHardwareAddress,
                                                    Destination = tapWorker.ifHardwareAddress,
                                                    EtherType   = EthernetType.None,
                                                };
                                                IpV4Layer ipV4Layer = new IpV4Layer
                                                {
                                                    Source             = packet.Ethernet.IpV4.Source,
                                                    CurrentDestination = tapWorker.ifProtocolAddress,
                                                    Fragmentation      = packet.Ethernet.IpV4.Fragmentation,
                                                    HeaderChecksum     = null, // Will be filled automatically.
                                                    Identification     = packet.Ethernet.IpV4.Identification,
                                                    Options            = packet.Ethernet.IpV4.Options,
                                                    Protocol           = packet.Ethernet.IpV4.Protocol,
                                                    Ttl           = packet.Ethernet.IpV4.Ttl,
                                                    TypeOfService = packet.Ethernet.IpV4.TypeOfService,
                                                };
                                                PayloadLayer payloadLayer = new PayloadLayer
                                                {
                                                    Data = new Datagram(packet.Ethernet.IpV4.Payload.ToArray()),
                                                };
                                                PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, payloadLayer);
                                                tapWorker.SendPacket(builder.Build(DateTime.Now));
                                            }
                                        }
                                    }
                                    //else if (packet.Ethernet.IpV4.Protocol == IpV4Protocol.Tcp)
                                    //{
                                    //    if (packet.Ethernet.IpV4.Destination == ifProtocolAddress)
                                    //    {
                                    //        lock (RoutingTable.lockObj)
                                    //            routingObject = RoutingTable.TranslateBack(packet);
                                    //        if (routingObject.ifIndex == -1)
                                    //            return;
                                    //        EthernetLayer ethernetLayer = new EthernetLayer
                                    //        {
                                    //            Source = TapWorker.ownHardwareAddress,
                                    //            Destination = TapWorker.ifHardwareAddress,
                                    //            EtherType = packet.Ethernet.EtherType,
                                    //        };
                                    //        IpV4Layer ipV4Layer = new IpV4Layer
                                    //        {
                                    //            Source = packet.Ethernet.IpV4.Source,
                                    //            CurrentDestination = TapWorker.ifProtocolAddress,
                                    //            Fragmentation = packet.Ethernet.IpV4.Fragmentation,
                                    //            HeaderChecksum = null, // Will be filled automatically.
                                    //            Identification = packet.Ethernet.IpV4.Identification,
                                    //            Options = packet.Ethernet.IpV4.Options,
                                    //            Protocol = packet.Ethernet.IpV4.Protocol,
                                    //            Ttl = packet.Ethernet.IpV4.Ttl,
                                    //            TypeOfService = packet.Ethernet.IpV4.TypeOfService,
                                    //        };
                                    //        TcpLayer tcpLayer = new TcpLayer
                                    //        {
                                    //            SourcePort = packet.Ethernet.IpV4.Tcp.SourcePort,
                                    //            DestinationPort = routingObject.localPort,
                                    //            Checksum = null, // Will be filled automatically.
                                    //            SequenceNumber = packet.Ethernet.IpV4.Tcp.SequenceNumber,
                                    //            AcknowledgmentNumber = routingObject.ack,
                                    //            ControlBits = packet.Ethernet.IpV4.Tcp.ControlBits,
                                    //            Window = packet.Ethernet.IpV4.Tcp.Window,
                                    //            UrgentPointer = packet.Ethernet.IpV4.Tcp.UrgentPointer,
                                    //            Options = packet.Ethernet.IpV4.Tcp.Options,
                                    //        };
                                    //        PayloadLayer payloadLayer = new PayloadLayer
                                    //        {
                                    //            Data = new Datagram(packet.Ethernet.IpV4.Tcp.Payload.ToArray()),
                                    //        };
                                    //        PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, tcpLayer, payloadLayer);
                                    //        MainThread.tapWorker.SendPacket(builder.Build(DateTime.Now));
                                    //    }
                                    //}
                                    else if (packet.Ethernet.IpV4.Protocol == IpV4Protocol.Udp)
                                    {
                                        if (packet.Ethernet.IpV4.Destination == ifProtocolAddress)
                                        {
                                            phyRoutingObject = RoutingTable.IsUdpConn(packet);
                                            if (phyRoutingObject.ifIndex == -1)
                                            {
                                                return;
                                            }
                                            EthernetLayer ethernetLayer = new EthernetLayer
                                            {
                                                Source      = tapWorker.ownHardwareAddress,
                                                Destination = tapWorker.ifHardwareAddress,
                                                EtherType   = packet.Ethernet.EtherType,
                                            };
                                            IpV4Layer ipV4Layer = new IpV4Layer
                                            {
                                                Source             = packet.Ethernet.IpV4.Source,
                                                CurrentDestination = tapWorker.ifProtocolAddress,
                                                Fragmentation      = packet.Ethernet.IpV4.Fragmentation,
                                                HeaderChecksum     = null, // Will be filled automatically.
                                                Identification     = packet.Ethernet.IpV4.Identification,
                                                Options            = packet.Ethernet.IpV4.Options,
                                                Protocol           = packet.Ethernet.IpV4.Protocol,
                                                Ttl           = packet.Ethernet.IpV4.Ttl,
                                                TypeOfService = packet.Ethernet.IpV4.TypeOfService,
                                            };
                                            UdpLayer udpLayer = new UdpLayer
                                            {
                                                SourcePort             = packet.Ethernet.IpV4.Udp.SourcePort,
                                                DestinationPort        = packet.Ethernet.IpV4.Udp.DestinationPort,
                                                Checksum               = null, // Will be filled automatically.
                                                CalculateChecksumValue = packet.Ethernet.IpV4.Udp.IsChecksumOptional,
                                            };
                                            PayloadLayer payloadLayer = new PayloadLayer
                                            {
                                                Data = new Datagram(packet.Ethernet.IpV4.Udp.Payload.ToArray()),
                                            };
                                            PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, udpLayer, payloadLayer);
                                            tapWorker.SendPacket(builder.Build(DateTime.Now));
                                        }
                                    }
                                }
                                else if (packet.Ethernet.IpV4.Fragmentation.Options == IpV4FragmentationOptions.MoreFragments ||
                                         packet.Ethernet.IpV4.Fragmentation.Options == IpV4FragmentationOptions.None && packet.Ethernet.IpV4.Fragmentation.Offset > 0)
                                {
                                    // TODO: fix warning spam
                                    if (Global.Config.LoadBalancer.ShowTrayTipsWarnings)
                                    {
                                        Global.ShowTrayTip("Load Balancer", "IP fragmentation detected on " + Name + ".\n\nIP fragmentation is not supported.", ToolTipIcon.Warning);
                                    }
                                    Global.WriteLog("Load Balancer: IP fragmentation detected on " + Name);
                                    //fragments = fragBuffer.Add(packet);
                                    //if (fragments != null)
                                    //    for (int i = 0; i < fragments.Count; i++)
                                    //    {
                                    //        IpV4Handler(fragments[i], fragments);
                                    //    }
                                }
                            }
                        });
                    }
                }
                catch (Exception e)
                {
                    if (ThreadActive.IsSet)
                    {
                        ThreadActive.Reset();
                        Global.WriteLog("Load Balancer: " + Name + " has disconnected");
                        if (Global.Config.Gadget.Debug)
                        {
                            Global.WriteLog(e.ToString());
                        }
                        Global.ShowTrayTip("Load Balancer", Name + " has disconnected", System.Windows.Forms.ToolTipIcon.Warning);
                    }
                }
            }
Exemple #25
0
 public void Stop()
 {
     ThreadActive.Reset();
     try { communicator.Break(); }
     catch { }
 }
 private void buttonStopCapture_Click(object sender, EventArgs e)
 {
     communicator.Break();
     label_Status.Text      = "Not Running";
     label_Status.ForeColor = System.Drawing.ColorTranslator.FromHtml("#FF0000");
 }
Exemple #27
0
 public static void Durdur()
 {
     communicator.Break();
 }
Exemple #28
0
        private void mWorkingThread_DoWork(object sender, DoWorkEventArgs e)
        {
            PacketDevice packetDevice = (PacketDevice)e.Argument;

            // Open the device
            PacketCommunicator communicator = packetDevice.Open(65536, PacketDeviceOpenAttributes.Promiscuous | PacketDeviceOpenAttributes.NoCaptureLocal | PacketDeviceOpenAttributes.MaximumResponsiveness, 30000);

            communicator.SetFilter("net (87.119.203.0/24 or 94.236.0.0/16 or 31.222.148.0/24) and port 80");
            Debug.WriteLine("Worker listening on " + packetDevice.Description + "...");

            // Retrieve the packets
            Packet        packet;
            DsoChatPacket chatPacket = null;

            do
            {
                // Thread should exit/cancel work
                if (mWorkingThread.CancellationPending == true)
                {
                    communicator.Break();
                    break;
                }

                // Pause?
                if (mPauseCapture)
                {
                    Thread.Sleep(1000);
                    continue;
                }

                // Wait for next packet
                PacketCommunicatorReceiveResult result = communicator.ReceivePacket(out packet);
                switch (result)
                {
                case PacketCommunicatorReceiveResult.Timeout:
                    continue;

                case PacketCommunicatorReceiveResult.Ok:
                    if (packet.Buffer != null && packet.Length > 0)
                    {
                        chatPacket = DsoChatPacket.Parse(packet.Buffer);
                        if (chatPacket == null || chatPacket.Messages.Count == 0)
                        {
                            // Failed to parse
                            mWorkingThread.ReportProgress(0);
                        }
                        else
                        {
                            mWorkingThread.ReportProgress(0, chatPacket.Clone());
                        }
                    }

                    break;

                default:
                    throw new InvalidOperationException("The result " + result + " should never be reached here");
                }
            } while (true);

            // Set result object to handle "Cancel" correctly
            e.Result = true;
        }
        // Callback function invoked by Pcap.Net for every incoming packet
        private void PacketHandler(Packet packet)
        {
            if (!BackgroundWorker1.CancellationPending == true)
            {
                try
                {
                    this.Invoke(new MethodInvoker(() => pbarProgressBar1.Visible = true));

                    if (packet.Ethernet.IpV4.Tcp.Payload != null)
                    {
                        Match  match;
                        string text = Encoding.ASCII.GetString(packet.Ethernet.IpV4.Tcp.Payload.ToMemoryStream().ToArray());

                        if (Properties.Settings.Default.filterOnSensorId.ToString().Length > 0)
                        {
                            match = Regex.Match(text.ToLower(), "sensor=" + Properties.Settings.Default.filterOnSensorId.ToString() + "|mt=pressure", RegexOptions.Singleline);
                        }
                        else if (Properties.Settings.Default.sensorType.ToString().Length > 0)
                        {
                            match = Regex.Match(text.ToLower(), "mt=" + Properties.Settings.Default.sensorType.ToString() + "|mt=pressure", RegexOptions.Singleline);
                        }
                        else
                        {
                            match = Regex.Match(text.ToLower(), "mt=", RegexOptions.Singleline);
                        }

                        string[] bridgeDataArray;
                        double   pressureOffset = Properties.Settings.Default.pressureOffset;

                        if (match.Success)
                        {
                            this.Invoke(new MethodInvoker(() => pbarProgressBar1.Value = progressBarValue(10)));

                            this.Invoke(new MethodInvoker(() => txtOutput.Text = txtOutput.Text.Replace(waitMessage, "")));

                            bridgeDataArray = text.Split('&');

                            if (text.IndexOf("mt=" + Properties.Settings.Default.sensorType.ToString(), StringComparison.CurrentCultureIgnoreCase) == -1)
                            {
                                noSensorDataIterations += 1;
                            }
                            else
                            {
                                noSensorDataIterations = 0;
                            }

                            foreach (string element in bridgeDataArray)
                            {
                                if (element.IndexOf("sensor=") == 0)
                                {
                                    sensorId = element.Substring(7, 5);
                                }

                                if (element.IndexOf("mt=") == 0)
                                {
                                    sensorType = element.Substring(3).ToLower();
                                }

                                if (Properties.Settings.Default.filterOnSensorId.ToString().Length == 0 || sensorId == Properties.Settings.Default.filterOnSensorId.ToString())
                                {
                                    if (element.IndexOf("winddir=") == 0 &&
                                        (Properties.Settings.Default.sensorTypeWind == "" || sensorType.IndexOf(Properties.Settings.Default.sensorTypeWind) != -1) &&
                                        (Properties.Settings.Default.sensorIdWind == "" || sensorId.IndexOf(Properties.Settings.Default.sensorIdWind) != -1))
                                    {
                                        windDirHex = element.Substring(8, 1);

                                        switch (windDirHex)
                                        {
                                        case "5":
                                            windDegrees = 0;
                                            break;

                                        case "7":
                                            windDegrees = 22.5;
                                            break;

                                        case "3":
                                            windDegrees = 45;
                                            break;

                                        case "1":
                                            windDegrees = 67.5;
                                            break;

                                        case "9":
                                            windDegrees = 90;
                                            break;

                                        case "B":
                                            windDegrees = 112.5;
                                            break;

                                        case "F":
                                            windDegrees = 135;
                                            break;

                                        case "D":
                                            windDegrees = 157.5;
                                            break;

                                        case "C":
                                            windDegrees = 180;
                                            break;

                                        case "E":
                                            windDegrees = 202.5;
                                            break;

                                        case "A":
                                            windDegrees = 225;
                                            break;

                                        case "8":
                                            windDegrees = 247.5;
                                            break;

                                        case "0":
                                            windDegrees = 270;
                                            break;

                                        case "2":
                                            windDegrees = 292.5;
                                            break;

                                        case "6":
                                            windDegrees = 315;
                                            break;

                                        case "4":
                                            windDegrees = 337.5;
                                            break;
                                        }
                                    }

                                    if (element.IndexOf("windspeed=") == 0 &&
                                        (Properties.Settings.Default.sensorTypeWind == "" || sensorType.IndexOf(Properties.Settings.Default.sensorTypeWind) != -1) &&
                                        (Properties.Settings.Default.sensorIdWind == "" || sensorId.IndexOf(Properties.Settings.Default.sensorIdWind) != -1))
                                    {
                                        windspeed = Math.Round(double.Parse(element.Substring(11, 5)) / 44.70400004, 1);

                                        dtWindData.Rows.Add(new object[] {
                                            DateTime.Now,
                                            windspeed
                                        });

                                        windGust = calcWindGust(windspeed);
                                    }

                                    if (element.IndexOf("temperature=") == 0 &&
                                        (Properties.Settings.Default.sensorTypeTemp == "" || sensorType.IndexOf(Properties.Settings.Default.sensorTypeTemp) != -1) &&
                                        (Properties.Settings.Default.sensorIdTemp == "" || sensorId.IndexOf(Properties.Settings.Default.sensorIdTemp) != -1))
                                    {
                                        if (element.Substring(13, 1) == "-")
                                        {
                                            temperature = Math.Round(double.Parse(element.Substring(14, 4)) * -1 / 100 * 9 / 5 + 32, 1);
                                        }
                                        else
                                        {
                                            temperature = Math.Round(double.Parse(element.Substring(14, 4)) / 100 * 9 / 5 + 32, 1);
                                        }
                                    }

                                    if (element.IndexOf("humidity=") == 0 &&
                                        (Properties.Settings.Default.sensorTypeHumidity == "" || sensorType.IndexOf(Properties.Settings.Default.sensorTypeHumidity) != -1) &&
                                        (Properties.Settings.Default.sensorIdHumidity == "" || sensorId.IndexOf(Properties.Settings.Default.sensorIdHumidity) != -1))
                                    {
                                        humidity = double.Parse(element.Substring(11, 3)) / 10;
                                    }

                                    if (element.IndexOf("rainfall=") == 0 &&
                                        (Properties.Settings.Default.sensorTypeRain == "" || sensorType.IndexOf(Properties.Settings.Default.sensorTypeRain) != -1) &&
                                        (Properties.Settings.Default.sensorIdRain == "" || sensorId.IndexOf(Properties.Settings.Default.sensorIdRain) != -1))
                                    {
                                        currRain = Math.Round(double.Parse(element.Substring(10, 6)) / 2540, 3);

                                        if (currRain > 0)
                                        {
                                            cumulRainDay     += currRain;
                                            cumulRainNoReset += currRain;
                                        }

                                        dtRainData.Rows.Add(new object[] { DateTime.Now, currRain });

                                        rainHour = rainLast60Minutes(currRain);
                                    }

                                    if (element.IndexOf("rssi=") == 0)
                                    {
                                        signal = int.Parse(element.Substring(5, 1));
                                    }

                                    if (element.IndexOf("battery=") == 0)
                                    {
                                        battery = element.Substring(8);
                                    }
                                }


                                // Get and process pressure data
                                if (element.IndexOf("C1=") == 0)
                                {
                                    c1 = Int32.Parse(element.Substring(3, 4), NumberStyles.HexNumber);
                                }

                                if (element.IndexOf("C2=") == 0)
                                {
                                    c2 = Int32.Parse(element.Substring(3, 4), NumberStyles.HexNumber);
                                }

                                if (element.IndexOf("C3=") == 0)
                                {
                                    c3 = Int32.Parse(element.Substring(3, 4), NumberStyles.HexNumber);
                                }

                                if (element.IndexOf("C4=") == 0)
                                {
                                    c4 = Int32.Parse(element.Substring(3, 4), NumberStyles.HexNumber);
                                }

                                if (element.IndexOf("C5=") == 0)
                                {
                                    c5 = Int32.Parse(element.Substring(3, 4), NumberStyles.HexNumber);
                                }

                                if (element.IndexOf("C6=") == 0)
                                {
                                    c6 = Int32.Parse(element.Substring(3, 4), NumberStyles.HexNumber);
                                }

                                if (element.IndexOf("C7=") == 0)
                                {
                                    c7 = Int32.Parse(element.Substring(3, 4), NumberStyles.HexNumber);
                                }

                                if (element.IndexOf("A=") == 0)
                                {
                                    a = Int32.Parse(element.Substring(3), NumberStyles.HexNumber);
                                }

                                if (element.IndexOf("B=") == 0)
                                {
                                    b = Int32.Parse(element.Substring(3), NumberStyles.HexNumber);
                                }

                                if (element.IndexOf("C=") == 0)
                                {
                                    c = Int32.Parse(element.Substring(3), NumberStyles.HexNumber);
                                }

                                if (element.IndexOf("D=") == 0)
                                {
                                    d = Int32.Parse(element.Substring(3), NumberStyles.HexNumber);
                                }

                                if (element.IndexOf("PR=") == 0)
                                {
                                    pr = Int32.Parse(element.Substring(3, 4), NumberStyles.HexNumber);
                                }

                                if (element.IndexOf("TR=") == 0)
                                {
                                    tr = Int32.Parse(element.Substring(3, 4), NumberStyles.HexNumber);

                                    d1 = pr;
                                    d2 = tr;

                                    if (d2 >= c5)
                                    {
                                        dut = d2 - c5 - ((d2 - c5) / Math.Pow(2, 7)) * ((d2 - c5) / Math.Pow(2, 7)) * a / Math.Pow(2, c);
                                    }
                                    else
                                    {
                                        dut = d2 - c5 - ((d2 - c5) / Math.Pow(2, 7)) * ((d2 - c5) / Math.Pow(2, 7)) * b / Math.Pow(2, c);
                                    }

                                    off = (c2 + (c4 - 1024) * dut / Math.Pow(2, 14)) * 4;

                                    sens = c1 + c3 * dut / Math.Pow(2, 10);

                                    x = sens * (d1 - 7168) / Math.Pow(2, 14) - off;

                                    p = x * 10 / Math.Pow(2, 5) + c7;

                                    t = 250 + dut * c6 / Math.Pow(2, 16) - dut / Math.Pow(2, d);

                                    pressure = Math.Round(p / 338.6 + pressureOffset, 2);
                                }

                                if (humidity > 0)
                                {
                                    dewpoint = ((((temperature - 32) / 1.8) - (14.55 + 0.114 * ((temperature - 32) / 1.8)) * (1 - (0.01 * humidity)) - Math.Pow(((2.5 + 0.007 *
                                                                                                                                                                  ((temperature - 32) / 1.8)) * (1 - (0.01 * humidity))), 3) - (15.9 + 0.117 * ((temperature - 32) / 1.8)) *
                                                 Math.Pow((1 - (0.01 * humidity)), 14)) * 1.8) + 32;
                                    dewpoint = Math.Round(dewpoint, 1);
                                }
                            }

                            if (txtOutput.Text.Length > 50000)
                            {
                                this.Invoke(new MethodInvoker(() => string.IsNullOrEmpty(txtOutput.Text)));
                            }

                            string wuResponse       = null;
                            string wBugResponse     = null;
                            string pwsResponse      = null;
                            string aWeatherResponse = null;

                            if (pressure > 0 & (humidity > 0 || Properties.Settings.Default.filterOnSensorId.ToString() == "water" && temperature > 0) & noSensorDataIterations < 5)
                            {
                                if (Properties.Settings.Default.postToWunderground == true)
                                {
                                    string wundergroundUpdateString = "http://rtupdate.wunderground.com/weatherstation/updateweatherstation.php?ID=" + Properties.Settings.Default.wuStation +
                                                                      "&PASSWORD="******"&dateutc=" +
                                                                      System.Uri.EscapeUriString(Convert.ToString(DateTime.Now.ToUniversalTime())) + "&winddir=" + windDegrees + "&windspeedmph=" + windspeed + "&tempf=" +
                                                                      temperature + "&rainin=" + rainHour + "&dailyrainin=" + cumulRainDay + "&baromin=" + pressure + "&dewptf=" + dewpoint + "&humidity=" + humidity +
                                                                      "&softwaretype=" + "Kevins%20Acu-Rapid%201217&action=updateraw&realtime=1&rtfreq=15" + "&windgustmph=" + windGust /*+ "&indoortempf=" + temperature +
                                                                                                                                                                                         * "&soiltempf=" + temperature*/;
                                    try
                                    {
                                        HttpWebRequest  request       = (HttpWebRequest)WebRequest.Create(wundergroundUpdateString);
                                        HttpWebResponse response      = (HttpWebResponse)request.GetResponse();
                                        Stream          receiveStream = response.GetResponseStream();
                                        StreamReader    readStream    = new StreamReader(receiveStream, Encoding.UTF8);
                                        wuResponse = readStream.ReadToEnd();

                                        readStream.Close();
                                        response.Close();

                                        if (wuResponse.IndexOf("success") != -1)
                                        {
                                            wuResponse = "ok";
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        wuResponse = "";
                                        this.Invoke(new MethodInvoker(() => txtOutput.Text = DateTime.Now + "\t" + "ERROR posting data to Weather Underground. " + ex.Message +
                                                                                             System.Environment.NewLine + txtOutput.Text));
                                    }
                                }
                                else
                                {
                                    wuResponse = "off";
                                }

                                if (Properties.Settings.Default.postToWeatherBug == true)
                                {
                                    string weatherBugUpdateString = "http://data.backyard2.weatherbug.com/data/livedata.aspx?ID=" + Properties.Settings.Default.wbPub + "&Key=" +
                                                                    Properties.Settings.Default.wbPwd + "&num=" + Properties.Settings.Default.wbStation + "&dateutc=" +
                                                                    System.Uri.EscapeUriString(Convert.ToString(DateTime.Now.ToUniversalTime())) + "&winddir=" + windDegrees + "&windspeedmph=" + windspeed +
                                                                    "&windgustmph=" + windGust + "&tempf=" + temperature + "&rainin=" + rainHour + "&dailyrainin=" + cumulRainDay + "&baromin=" + pressure +
                                                                    "&dewptf=" + dewpoint + "&humidity=" + humidity + "&softwaretype=Kevin%27s%20Acu-Link";
                                    try
                                    {
                                        HttpWebRequest  request       = (HttpWebRequest)WebRequest.Create(weatherBugUpdateString);
                                        HttpWebResponse response      = (HttpWebResponse)request.GetResponse();
                                        Stream          receiveStream = response.GetResponseStream();
                                        StreamReader    readStream    = new StreamReader(receiveStream, Encoding.UTF8);
                                        wBugResponse = readStream.ReadToEnd();

                                        readStream.Close();
                                        response.Close();

                                        if (wBugResponse == "Successfully Received QueryString Data")
                                        {
                                            wBugResponse = "ok";
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        wBugResponse = "";
                                        this.Invoke(new MethodInvoker(() => txtOutput.Text = DateTime.Now + "\t" + "ERROR posting data to Weatherbug. " + ex.Message +
                                                                                             System.Environment.NewLine + txtOutput.Text));
                                    }
                                }
                                else
                                {
                                    wBugResponse = "off";
                                }

                                if (Properties.Settings.Default.postToPws == true)
                                {
                                    string pwsUpdateString = "http://www.pwsweather.com/pwsupdate/pwsupdate.php?ID=" + Properties.Settings.Default.pwsStation + "&PASSWORD="******"&dateutc=" +
                                                             DateTime.Now.ToUniversalTime().ToString("yyyy-MM-dd+HH\\%3Amm\\%3Ass") + "&winddir=" + windDegrees + "&windspeedmph=" + windspeed +
                                                             "&windgustmph=" + windGust + "&tempf=" + temperature + "&rainin=" + rainHour + "&dailyrainin=" + cumulRainDay + "&baromin=" + pressure +
                                                             "&dewptf=" + dewpoint + "&humidity=" + humidity + "&action=updateraw";

                                    //this.Invoke(new MethodInvoker(() => txtOutput.Text = DateTime.Now + "\t" + pwsUpdateString +
                                    //        System.Environment.NewLine + txtOutput.Text));

                                    try
                                    {
                                        HttpWebRequest  request       = (HttpWebRequest)WebRequest.Create(pwsUpdateString);
                                        HttpWebResponse response      = (HttpWebResponse)request.GetResponse();
                                        Stream          receiveStream = response.GetResponseStream();
                                        StreamReader    readStream    = new StreamReader(receiveStream, Encoding.UTF8);
                                        pwsResponse = readStream.ReadToEnd();

                                        readStream.Close();
                                        response.Close();

                                        if (pwsResponse.IndexOf("Data Logged and posted in METAR mirror") >= 0)
                                        {
                                            pwsResponse = "ok";
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        pwsResponse = "";
                                        this.Invoke(new MethodInvoker(() => txtOutput.Text = DateTime.Now + "\t" + "ERROR posting data to PWSweather. " + ex.Message +
                                                                                             System.Environment.NewLine + txtOutput.Text));
                                    }
                                }
                                else
                                {
                                    pwsResponse = "off";
                                }

                                if (Properties.Settings.Default.postToAWeather == true)
                                {
                                    if (skipUpdateCount == 0 || skipUpdateCount >= skipUpdateInterval)
                                    {
                                        skipUpdateCount = 0;

                                        string aWeatherUpdateString = "http://www.anythingweather.com/feeds/load/WXDATAPOST.ASP?username="******"&password="******"&version=1&WXData=" +
                                                                      DateTime.Now.ToString("yyyy\\%2DMM\\%2Ddd+HH:mm:ss") + "%2C" + temperature + "%2C" + dewpoint + "%2C" +
                                                                      humidity + "%2C" + pressure + "%2C" + windDegrees + "%2C" + windspeed + "%2C" + cumulRainDay + "%2C%2C%2C" + windGust +
                                                                      "%2C%0D";

                                        try
                                        {
                                            HttpWebRequest  request       = (HttpWebRequest)WebRequest.Create(aWeatherUpdateString);
                                            HttpWebResponse response      = (HttpWebResponse)request.GetResponse();
                                            Stream          receiveStream = response.GetResponseStream();
                                            StreamReader    readStream    = new StreamReader(receiveStream, Encoding.UTF8);
                                            aWeatherResponse = readStream.ReadToEnd();

                                            readStream.Close();
                                            response.Close();

                                            if (aWeatherResponse == "")
                                            {
                                                aWeatherResponse = "ok";
                                                //aWeatherResponse = aWeatherUpdateString;
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            aWeatherResponse = "";
                                            this.Invoke(new MethodInvoker(() => txtOutput.Text = DateTime.Now + "\t" + "ERROR posting data to Anything Weather. " + ex.Message +
                                                                                                 System.Environment.NewLine + txtOutput.Text));
                                        }
                                    }
                                    else
                                    {
                                        aWeatherResponse = "wait " + skipUpdateCount.ToString();
                                    }
                                }
                                else
                                {
                                    aWeatherResponse = "off";
                                }

                                skipUpdateCount += 1;

                                if (Properties.Settings.Default.writeToCSV == true)
                                {
                                    string newFileName;

                                    if (Properties.Settings.Default.csvFilePath == "")
                                    {
                                        newFileName = "weather.csv";
                                    }
                                    else
                                    {
                                        newFileName = Properties.Settings.Default.csvFilePath;
                                    }

                                    string weatherData = DateTime.Now + "," + temperature + "," + humidity + "," + windspeed + "," + windGust + "," + windDegrees + "," +
                                                         pressure + "," + rainHour + "," + cumulRainDay + "," + dewpoint + Environment.NewLine;

                                    if (!File.Exists(newFileName))
                                    {
                                        string fileHeader = "Local Time" + "," + "Temperature" + "," + "Humidity" + "," + "Wind MPH" + "," + "Wind Gust" + "," + "Wind Dir" + "," +
                                                            "Pressure" + "," + "Rain Hour" + "," + "Rain Day" + "," + "Dewpoint" + Environment.NewLine;

                                        File.WriteAllText(newFileName, fileHeader);
                                    }

                                    File.AppendAllText(newFileName, weatherData);
                                }
                            }
                            else
                            {
                                wuResponse       = "Need more data";
                                wBugResponse     = "Need more data";
                                pwsResponse      = "Need more data";
                                aWeatherResponse = "Need more data";
                            }

                            this.Invoke(new MethodInvoker(() => txtOutput.Text = DateTime.Now + "   " + "T:" + temperature.ToString("F1") + "   " + "H:" + humidity + "   " + "W:" +
                                                                                 windDegrees + "\t" + "WS:" + windspeed.ToString("F1") + "\t" + "Gust:" + windGust.ToString("F1") + "\t" + "RDAY:" + cumulRainDay.ToString("F2") +
                                                                                 "  " + "RHR:" + rainHour.ToString("F2") + "   " + "BAR:" + pressure.ToString("F2") + "   " + "DEW:" + dewpoint.ToString("F1") + "   " + "SI: " + sensorId +
                                                                                 "  ST: " + sensorType + "   " + "WU: " + wuResponse + "  " + "WB: " + wBugResponse + "  " + "PWS: " + pwsResponse + "  " + "AW: " + aWeatherResponse +
                                                                                 System.Environment.NewLine + txtOutput.Text));

                            this.Invoke(new MethodInvoker(() => txtBattery.Text = battery));

                            if (battery == "normal")
                            {
                                this.Invoke(new MethodInvoker(() => txtBattery.BackColor = Control.DefaultBackColor));
                            }
                            else
                            {
                                this.Invoke(new MethodInvoker(() => txtBattery.BackColor = Color.FromArgb(247, 247, 124)));
                            }

                            this.Invoke(new MethodInvoker(() => txtSignal.Text = signal.ToString()));

                            switch (signal)
                            {
                            case 0:
                                this.Invoke(new MethodInvoker(() => txtSignal.BackColor = Color.Red));
                                break;

                            case 1:
                                this.Invoke(new MethodInvoker(() => txtSignal.BackColor = Color.FromArgb(247, 247, 124)));
                                break;

                            case 2:
                            case 3:
                            case 4:
                                this.Invoke(new MethodInvoker(() => txtSignal.BackColor = Control.DefaultBackColor));
                                break;
                            }

                            this.Invoke(new MethodInvoker(() => txtLastUpdated.Text = DateTime.Now.ToString()));


                            if (DateTime.Now.Day != previousDay)
                            {
                                cumulRainDay = 0;
                            }

                            previousDay = DateTime.Now.Day;

                            previousRainReading = currRain;

                            if (noSensorDataIterations >= 5)
                            {
                                this.Invoke(new MethodInvoker(() => txtOutput.Text = DateTime.Now + "\t" + "INFO: Not receiving data from sensor. Low batteries? Too far away?" +
                                                                                     System.Environment.NewLine + txtOutput.Text));
                                battery      = "unknown";
                                signal       = 0;
                                signalFails += 1;
                            }

                            this.Invoke(new MethodInvoker(() => txtSignalFails.Text = signalFails.ToString()));
                        }
                    }
                }
                catch (NullReferenceException ex)
                {
                    //Keep going
                }
                catch (Exception ex)
                {
                    this.Invoke(new MethodInvoker(() => txtOutput.Text = "ERROR: " + ex.Message + " " + ex.Source + System.Environment.NewLine + txtOutput.Text));
                }
            }
            else
            {
                communicator.Break();
                BackgroundWorker1.CancelAsync();
                BackgroundWorker1.Dispose();
            }
        }