1

I'm trying to develop a method that checks if an IP direction is reachable and I found a similar question but it doesn't work Android Application Ping IP number

private void existePingServidor(){
    InetAddress in;
       try{
            in = InetAddress.getByName("90.0.0.122");

       if (in.isReachable(5000)){
           pingServidor = true;
           Log.v("true","He pasado por aquí");
       }
       else
           pingServidor = false;
       Log.v("false", "No he podido alcanzar la ip");

    }

    catch(Exception  e){
        e.printStackTrace();
    }
}

The problem seems that InetAddress.getByName("90.0.0.122"); returns null

¿Can you explain me what is the proper way to ping a Ip in android studio please?

Markus Kauppinen
  • 3,025
  • 4
  • 20
  • 30
Adriiboom
  • 85
  • 13
  • Something good to know, `Log.v("false", "No he podido alcanzar la ip");` will always get called because you aren't using brackets correctly in the else-statement. – Zun Oct 03 '19 at 08:30
  • Also, could you explain why you want to ping a site to check if it's available? Your problem might be solvable in an easier way. – Zun Oct 03 '19 at 08:31
  • Hi, thank for your answer, it's true about the log, but i get an android.os.NetworkOnMainThreadException that causes the Log to not display anything. About the reassons of checking the IP is because if the IP is the 90.0.0.122 then the aplication has to do other things. – Adriiboom Oct 03 '19 at 09:32
  • Call the function in a separate thread. There are a lot of questions about NetworkOnMainThreadException on Google. Example: https://stackoverflow.com/questions/6343166/how-do-i-fix-android-os-networkonmainthreadexception – Zun Oct 03 '19 at 09:34

1 Answers1

1

Try getByAddress instead:

    byte [] ip = {90, 0, 0, 122};
    addr = InetAddress.getByAddress(ip);
    addr.isReachable(5000);
selbie
  • 100,020
  • 15
  • 103
  • 173