Reputation: 21
I am trying to capture network packets from several IPs at the same time using threads, but i get this exception "An operation on a socket could not be performed because the system lacked sufficient buffer space or because a queue was full". I am new to threads and sockets. Exception come from "mainSocket.BeginReceive(_data, 0, _data.Length, SocketFlags.None, OnReceive, null);"
IPHostEntry HosyEntry = Dns.GetHostEntry((Dns.GetHostName()));
if (HosyEntry.AddressList.Length > 0)
{
foreach (IPAddress ip in HosyEntry.AddressList)
{
if (ip.IsIPv6LinkLocal == false)
{
SetIp ipAdd = new SetIp();
ipAdd.SetIpAdd(ip);
}
}
}
class SetIp
{
private Socket mainSocket;
private byte[] _data = new byte[4096];
public void SetIpAdd(IPAddress address)
{
mainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
mainSocket.Bind(new IPEndPoint(address, 0));
Thread MyThread = new Thread(new ThreadStart(() =>{
while (true)
{
mainSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, true);
byte[] byTrue = new byte[] { 1, 0, 0, 0 };
byte[] byOut = new byte[] { 1, 0, 0, 0 };
mainSocket.IOControl(IOControlCode.ReceiveAll, byTrue, byOut);
mainSocket.BeginReceive(_data, 0, _data.Length, SocketFlags.None, OnReceive, null);
} }));
MyThread.Start();
}
private void OnReceive(IAsyncResult ar)
{
var received = mainSocket.EndReceive(ar);
Parse(_data, received);
mainSocket.BeginReceive(_data, 0, _data.Length, SocketFlags.None, OnReceive, null);
}
private void Parse(byte[] data, int size)
{
IPHeader ipHeader = new IPHeader(data, size);
Console.WriteLine( ipHeader.SourceIP.ToString());
}
Upvotes: 0
Views: 323
Reputation: 21
Used Receive method instead of the BeginReceive method.
mainSocket.Receive(byteData, 0, byteData.Length, SocketFlags.None);
ParseData(byteData, byteData.Length);
Upvotes: 1
Reputation: 171236
You are calling BeginReceive
infinitely often in a hot loop. This causes infinitely many IOs to queue up.
Probably, you want to use synchronous IO because it is simpler to use. Alternatively, only issue the next reado nce the last one has completed.
Upvotes: 1