How can I wrap the ReceivePackets into Thread/Task/Backgroundworker? I tried to use all these, but I got error: "System.AccessViolationException system.accessviolationexception attempted to read or write protected memory"
Thats my try. thread creation:
PacketDevice selectedDevice = allDevices[deviceIndex - 1];
// Open the device
using (communicator =
selectedDevice.Open(65536, // portion of the packet to capture
// 65536 guarantees that the whole packet will be captured on all the link layers
PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode
1000)) // read timeout
{
Console.WriteLine("Listening on " selectedDevice.Description "...");
// start the capture
pThread.Start();
}
recvP function and packet handler:
private void recvP()
{
communicator.ReceivePackets(0, PacketHandler);
}
// Callback function invoked by Pcap.Net for every incoming packet
private void PacketHandler(Packet packet)
{
UdpDatagram datagram = packet.Ethernet.IpV4.Udp;
if (datagram != null && datagram.SourcePort == 6969)
{
MemoryStream stream = datagram.Payload.ToMemoryStream();
byte[] byteStream = stream.ToArray();
current_packet_id = BitConverter.ToUInt16(byteStream, 0);
Console.WriteLine("Got chunk number: " current_packet_id);
if (current_packet_id < last_packet_id) // new image (first chunk of the image)
{
if (!firstImage)
ShowImage(); // show image if all his chunks arrived
data.Clear(); // clear all data from past images
data.AddRange(byteStream.Skip(2).Take(byteStream.Length - 2).ToList());
}
else // next packets (same chunk continues)
data.AddRange(byteStream.Skip(2).Take(byteStream.Length - 2).ToList());
last_packet_id = current_packet_id;
}
}
CodePudding user response:
I got it, the fix was to move the using construction into the thread function, and leave only the pThread.Start()
private void recvP()
{
// open the device
using (communicator =
selectedDevice.Open(65536, // portion of the packet to capture
// 65536 guarantees that the whole packet will be captured on all the link layers
PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode
1000)) // read timeout
{
Console.WriteLine("Listening on " selectedDevice.Description "...");
communicator.ReceivePackets(0, PacketHandler);
}
}