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; } }