3

I am using System.Net.NetworkInformation.Ping class to ping a certain Ip. I am working on an Android Form application using Xamarin and visual Studio 2015. Here is the code that I am using.

   int timeout = 100;
   Ping ping= new Ping();
   PingReply reply = ping.Send("209.197.25.1", timeout);

   if (reply != null && reply.Status == IPStatus.Success)
       return reply.RoundtripTime;
   if (reply != null && reply.Status == IPStatus.TimedOut)
       return -1;

One thing is that if my WiFi is connected then I never get timed-out no matter how small i give the timeout value (as low as 1), and the reply.RoundtripTime is greater than the timeout(almost 300 for this server from my location). But if my WiFi is off then I get timed-out according to the time I specified.

I also tried to run the same code on C# console application and it works perfectly fine there. I have also tried different servers and the result is same. Can someone tell me what I am doing wrong? Some people figured that I am using this code to check if the destination is available, but I am not, I am interested in the round trip time from one pc to another.

Umer Javaid
  • 200
  • 1
  • 7
  • 2
    Is it absolutely required that you do a ping like this? There is also a plugin that can tell you if a certain address is reachable. Check it out [here](https://github.com/jamesmontemagno/ConnectivityPlugin) – Gerald Versluis Aug 02 '16 at 08:04
  • try a webrequest if possible instead of a ping – giammin Aug 02 '16 at 08:29
  • ICMP might not work greatly in all cases (forwarding might be disabled), so if you do want to test availability, try other approaches. – Lex Li Aug 02 '16 at 10:23
  • @GeraldVersluis I want to find the time it takes for a packet to go to a server and come back, so m using ping. I am not sure if there is some other class that can do the same. – Umer Javaid Aug 03 '16 at 17:12

2 Answers2

2

ping.Send() always fail when emulating, so you need to make the ping through a Java Runtime command, just add this:

Java.Lang.Process p1 = Java.Lang.Runtime.GetRuntime().Exec("ping -c 1 www.stackoverflow.com");
int returnVal = p1.WaitFor();

You will get returnVal = 1 if it is OK or returnVal = 2 if error, and that's all.

Windgate
  • 365
  • 1
  • 4
  • 14
  • 2
    "always fail when emulating" saved my sanity. Tanks – juwens Feb 26 '21 at 22:36
  • There is a complex solution to this by adding a second network to the qemu network, which supports ICMP: https://gist.github.com/manojrege/9e491f902767898af1af1665c8c531db – juwens Feb 26 '21 at 22:47
0

@Umer Javaid I tryed this plugin and found that it is not working correctly. This plugin based on Java.InetAddress.GetByName(host).IsReachable(msTimeout); And there is problems and issues with this method Why does InetAddress.isReachable return false, when I can ping the IP address?

Community
  • 1
  • 1
Vitaly
  • 91
  • 9