c# pingreply ipaddress in win vista+

Hello,

I'm using the following code to perform a ping:

Ping p = new Ping();
p.PingCompleted += new PingCompletedEventHandler(p_PingCompleted);
p.SendAsync(new IPAddress(new byte[] { 10, 2, 1, 25 }), 1000);
p.Dispose();

And then I'm catching the reply this way:

void p_PingCompleted(object sender, PingCompletedEventArgs e) {
PingReply pr = e.Reply;
IPAddress the_pinged_ip = pr.Address;
}

My question, this works perfectly fine on windows XP, but: on Vista I get a reply from 10.2.1.139 (my own PC's address) if the ping fails. (similar to the 'ping' command in DOS)

Is there a way to find the ACTUAL ip that was pinged?

Thanks in advance,

Sam



Roger affirmative, mi amigo.  


Your solution I believe lies in a parameter of the Ping.SendAsync method, known as Object userToken.

Change these lines it should work fine.

Change your sender to:
System.Net.IPAddress ip = (new byte[] { 10, 2, 1, lowByte }); //or whatever code works with your for..next loop.
p.SendAsync(ip, 1000, ip) //the second "ip" fills the userToken parameter.

then in the reply:
System.Net.IPAddress CallerIP = (System.Net.IPAddress)e.UserState;

That should work just fine. If you're getting errors, you might have to send it through as a string and convert it back at the other end, but I don't think you'll have to go thru that much trouble. Let me know if it doesn't work.


Oh My F*cking God !!!!
You have no idea how much I love you right now, I've been searching for something like this for 2 days straight, I've tried to find ways around it using self programmed ping classes with sockets, .. but nothing worked

this does the trick,
thank you soooo much.

God bless you,
Kind regards,

Sam
原文地址:https://www.cnblogs.com/1971ruru/p/2279575.html