I was reading through the thread on this topic towards the end of
march. It was mentioned that when he author multi-threads his ping
program one thread may get the response from another. It was said this
was expect since ICMP doesn't use ports so the framework can't
determine who sent the original packet. The proposed solution was to
check and make sure that the incoming source IP matches the thread that
sent it. I tried implementing this but cannot seem to get it to work.
In my code below when I try to check for the endpoint who sent the
reply I always get an exception. Any suggestions?
Thanks,
Mark
Here is the code section:
if (ClientSocket.SendTo(sendBuffer, remoteEP) <= 0)
throw new SocketException();
ClientSocket.BeginReceiveFrom(new byte[sendBuffer.Length + 20], //
Receive byte array
0, // offset in byte array
sendBuffer.Length + 20, //size to receive
SocketFlags.None, //Socket flages
ref remoteEP, // endpoint
new AsyncCallback(RecvCallback), // Asyn callback
null); // object that contains state info
private void RecvCallback(IAsyncResult ar)
{
int bytesReceived = 0;
try
{
Console.WriteLine(ClientSocket.RemoteEndPoint.ToString());
bytesReceived = ClientSocket.EndReceiveFrom(ar, ref remoteEP);
//were any bytes received?
if (bytesReceived > 0) //Yes
ResponseTime = s.Peek();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
This exception is generated when it hits the line has the
ClientSocket.RemoteEndPoint:
A request to send or receive data was disallowed because the socket is
not connected and (when sending on a datagram socket using a sendto
call) no address was supplied
mgenti@gmail.com - 02 Oct 2005 22:53 GMT
So I think I found a solution. I ended up not doing async (since I
really didn't want to anyways) and this is what I did:
bool ContinueWaiting = true;
while (ContinueWaiting)
{
byte[] recvBuffer = new byte[sendBuffer.Length + 20];
int bytesRecvd = ClientSocket.ReceiveFrom(recvBuffer,
SocketFlags.Peek, ref remoteEP);
byte[] senderBytes = new byte[4] {recvBuffer[12], recvBuffer[13],
recvBuffer[14], recvBuffer[15]};
IPAddress senderIP = new IPAddress(senderBytes);
if (IPAddress.Equals(senderIP, Host))
{
if (ClientSocket.ReceiveFrom(recvBuffer, ref remoteEP) <= 0)
throw new SocketException();
Stop = s.Peek(); // Stop the StopWatch
if (recvBuffer[20] != Convert.ToByte(0)) //Is the return
ICMP message an echo reply
Stop = Convert.ToInt32(recvBuffer[20] * -1);
ContinueWaiting = false;
}
else
{
//Console.WriteLine(senderIP.ToString() + " did not match " +
Host.ToString());
}
}
BTW, this is for a free windows ping utility program that I am writing.
Check out the project at sourceforge.net/projects/pingutil and feel
free to contribute or make any suggestions.
Thanks!
--Mark