问题
Currently trying to implement a simple ping program to teach myself about network programming in C# and .NET.
I have managed to initialize a raw socket and correctly build an ICMP echo request packet. When running my program, Wireshark confirms that I am sending an Echo Request to the desired destination, however the remote machine will never send back an echo reply. I have tried sending to multiple machines all with the same result (and each of these machines can be pinged using the Windows ping utility). My code goes like this:
IcmpPacket echoReq = new IcmpPacket;
/*Some code to initialize packet*/
rawSocket.Send(echoReq, destinationIP); //syntax may be wrong, dont have the code infront of me sorry
rawSocket.ReceiveFrom(buffer, remoteEndpoint);
If anyone could suggest any reasons why the remote machines do not send any reply, I'd be very grateful.
回答1:
It's hard to know for sure from the information in your question. There are just too many things that can go wrong. But here are a few that I would start checking through.
- The ICMP packet could be incorrectly formatted. I would use wireshark to compare the result of your custom ping packet to that of a known functioning utility to see if there are any differences
- The
destinationIP
andremoteEndpoint
values could point to different addresses. Seems unlikely but wanted to call it out - The IP in question could be simply rejecting the ping request. I would verify with another tools that it is returning pings
- The firewall could be getting in the way. I would disable it temporarily and then rerun my program to see if that was the cause.
回答2:
Do you have to build your own packet? There is the Ping class otherwise
http://msdn.microsoft.com/en-us/library/system.net.networkinformation.ping.aspx
EDIT:
Ping pingSender = new Ping ();
PingReply reply = pingSender.Send ("www.contoso.com");
if (reply.Status == IPStatus.Success)
{
Console.WriteLine ("Address: {0}", reply.Address.ToString ());
Console.WriteLine ("RoundTrip time: {0}", reply.RoundtripTime);
Console.WriteLine ("Time to live: {0}", reply.Options.Ttl);
Console.WriteLine ("Don't fragment: {0}", reply.Options.DontFragment);
Console.WriteLine ("Buffer size: {0}", reply.Buffer.Length);
}
else
{
Console.WriteLine (reply.Status);
}
来源:https://stackoverflow.com/questions/8838120/c-sharp-raw-socket-receiving-packets