Im building application which should show network traffic per process.Im using SharpPcap.
Idea is to start capturing network traffic on new threads,one thread per process.How it should work:Start capture on new thread,wait for 2000 ms,stop capture,Show in message box amount of traffic captured(for now),end thread.
Problem:For certain processes message box is showed multiple times meaning that method is called more times than it should be.Im using list(I made sure that every process in list is unique,no error there) and foreach loop.
Method StartThreads is called in foreach loop,for each process in list.
void StartThreads()
{
//filter gets created
IPAddress[] IpAddressList = Dns.GetHostByName(Dns.GetHostName()).AddressList;
string ip = IpAddressList[0].ToString();
string filterReceived = "dst host " + ip + " and " + filter_partReceived;
DownloadForListview procDownload = new DownloadForListview(filterReceived, 2,processIDq,ReturnDevice());
Thread t2 = new Thread(() => procDownload.ReceivedPackets());
t2.IsBackground = true;
t2.Start();
}
}
Thread which should capture network traffic:
class DownloadForListview
{
private static string FilterDownload;
private static int adapterIndex;
private static int ProcessID;
ICaptureDevice uredaj;
protected static long dataLenght;
protected static double dataPerSec;
public DownloadForListview(string filter, int adapterId,int pid,ICaptureDevice d)
{
uredaj = d;
FilterDownload = filter;
adapterIndex = adapterId;
ProcessID = pid;
}
public void ReceivedPackets()
{
uredaj.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketReceived);
uredaj.Filter = FilterDownload;
uredaj.StartCapture();
Thread.Sleep(2000);
uredaj.StopCapture();
dataPerSec = Math.Round(dataLenght / 2d,3);
MessageBox.Show("Pid:"+ProcessID+"->" + FilterDownload+"->" + dataLenght.ToString());
}
private static void device_OnPacketReceived(object sender, CaptureEventArgs e)
{
dataLenght += e.Packet.Data.Length;
}
}
I also noticed that sometimes,in debug mode,i get sharppcap exception:"thread was aborted after 00:00:02" but i dont think that does matter.