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());
}
_dataline where you initialize it please. - Haney