I have list of ipaddress. I am using udp protocol to send request to these addressses asynchronously to an snmp agent. The available snmp agent on these address reply. When I call BeginSendTo with these addresses, devices are replying in random order. When ReceiveBeginReceiveFrom is called and stateobject object is constructed. The RemoteIPEndPoint doesn't belong to the machine that replied instead it belongs to other machine. Is my approach of calling BeginSendTo is correct? If Yes, y stateobject instance doesn't give me correct remoteendpoint that replied? I am posting my code. Please correct if case something is missing.
public class Test
{
Socket udpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
class StateObject
{
public Socket Socket { get; set; }
public byte[] DataBuff { get; set; }
public IPEndPoint RemoteEndPoint { get; set; }
//validation are omited
public static StateObject Create(Socket s,byte[] dataBuf,IPEndPoint endpoint)
{
return new StateObject() { Socket = s, DataBuff = dataBuf, RemoteEndPoint = endpoint };
}
public static StateObject Transform(object objectstate)
{
return objectstate as StateObject;
}
}
public void Fx()
{
//list of ip address from 190.188.191.1 - 190.188.191.100
var address = new[] {
IPAddress.Parse("190.188.191.1"),
IPAddress.Parse("190.188.191.100")
};
byte[] dataGram = new byte[1024];
foreach (IPAddress item in address)
{
udpSocket.BeginSendTo(dataGram,
0,
dataGram.Length,
SocketFlags.None,
new IPEndPoint(item, 161),
SendComplete,
StateObject.Create(udpSocket, null, new IPEndPoint(item, 161))
);
}
}
private void SendComplete(IAsyncResult ar)
{
StateObject obj = StateObject.Transform(ar.AsyncState);
obj.Socket.EndSendTo(ar);//ignore the no of bytes send for now
byte[] receivedBytes = new byte[1024 * 4];//assume 4kb is enough for response
var ep = obj.RemoteEndPoint as EndPoint;
obj.Socket.BeginReceiveFrom(receivedBytes,
0,
receivedBytes.Length,
SocketFlags.None,
ref ep,
ReceivedData,
StateObject.Create(obj.Socket, receivedBytes, obj.RemoteEndPoint)
);
}
private void ReceivedData(IAsyncResult ar)
{
StateObject obj = StateObject.Transform(ar.AsyncState);
var ep = obj.RemoteEndPoint as EndPoint;
//response received from ip 190.188.191.2 but in stateobject.remoteendpoint will give 190.188.191.1
var bytesReceived = obj.Socket.EndReceiveFrom(ar,ref ep);
byte[] data = new byte[bytesReceived];
Array.Copy(obj.DataBuff,data, bytesReceived);
}
}