Search code examples
mauiping

Ping an IP address or a host from .Net MAUI App


I have created a brand new .net MAUI App (VS 2022 Community).

I am trying to ping an IP address from my MainPage.

My code:

IPAddress ipAddress = IPAddress.Parse(hostOrIp);

PingReply reply = await ping.SendPingAsync(ipAddress);
if (reply.Status == IPStatus.Success)
{
    return true;
}
else
{
    return false;
}

However, the code above does not seem to work at all, not on Android emulator not on a physical Android device either. The requisite permissions are already taken care of. I am getting a "System.Net.NetworkInformation.IPStatus.TimedOut" reply every time even to well known IP addresses like 8.8.8.8.

What could be the problem?


Solution

  • I ran the program on emulator using any other IP, it will be TimedOut as you said:

    private async void Button_Clicked(object sender, EventArgs e)
    {
        try
        {
            Ping pingSender = new Ping();
            PingReply reply = await pingSender.SendPingAsync("47.75.18.65");
            if (reply.Status == IPStatus.Success)
            {
                //...
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
    

    enter image description here

    However, if I test it on real device, it will be successful.

    There is another way to achieve it when run the program on emulator. You can make the ping by a Java Runtime command:

    private async void Button_Clicked(object sender, EventArgs e)
    {
    
    #if ANDROID
            Java.Lang.Process p1 = Java.Lang.Runtime.GetRuntime().Exec("ping -c 1 47.75.18.65");
            int returnVal = p1.WaitFor();
    #endif
    
    }
    

    returnVal is 1 indicating success, and here is the effect.

    Wish these can help you.