Comment Ping IP externe à partir de Java Android


Je développe une application Ping pour Android 2.2.

J'essaie mon code et cela fonctionne, mais seulement dans les adresses IP locales, c'est mon problème, je veux aussi faire du ping vers des serveurs externes.

Voici mon code:

  private OnClickListener milistener = new OnClickListener() {
    public void onClick(View v) {
        TextView info = (TextView) findViewById(R.id.info);
        EditText edit = (EditText) findViewById(R.id.edit);
        Editable host = edit.getText();
        InetAddress in;
        in = null;
        // Definimos la ip de la cual haremos el ping
        try {
            in = InetAddress.getByName(host.toString());
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // Definimos un tiempo en el cual ha de responder
        try {
            if (in.isReachable(5000)) {
                info.setText("Responde OK");
            } else {
                info.setText("No responde: Time out");
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            info.setText(e.toString());
        }
    }
};

Ping 127.0.0.1 - > OK
Ping 8.8.8.8 (DNS Google) - > Délai d'expiration

J'ai aussi mis la ligne suivante au manifeste XML:

<uses-permission android:name="android.permission.INTERNET"></uses-permission>

Quelqu'un peut-il me suggérer où je fais mal?

Author: swiftBoy, 2010-10-11

9 answers

J'ai essayé le code suivant qui fonctionne pour moi.

private boolean executeCommand(){
        System.out.println("executeCommand");
        Runtime runtime = Runtime.getRuntime();
        try
        {
            Process  mIpAddrProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
            int mExitValue = mIpAddrProcess.waitFor();
            System.out.println(" mExitValue "+mExitValue);
            if(mExitValue==0){
                return true;
            }else{
                return false;
            }
        }
        catch (InterruptedException ignore)
        {
            ignore.printStackTrace();
            System.out.println(" Exception:"+ignore);
        } 
        catch (IOException e) 
        {
            e.printStackTrace();
            System.out.println(" Exception:"+e);
        }
        return false;
    }
 47
Author: krishna5688, 2015-05-18 15:16:13

Exécutez l'utilitaire ping dans la commande d'Android et analysez la sortie (en supposant que vous disposez des autorisations root)

Voir l'extrait de code Java suivant:

executeCmd("ping -c 1 -w 1 google.com", false);

public static String executeCmd(String cmd, boolean sudo){
    try {

        Process p;
        if(!sudo)
            p= Runtime.getRuntime().exec(cmd);
        else{
            p= Runtime.getRuntime().exec(new String[]{"su", "-c", cmd});
        }
        BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));

        String s;
        String res = "";
        while ((s = stdInput.readLine()) != null) {
            res += s + "\n";
        }
        p.destroy();
        return res;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "";

}
 11
Author: Jim Huang, 2012-07-30 23:02:44

Dans mon cas, ping fonctionne à partir du périphérique mais pas de l'émulateur. J'ai trouvé cette documentation: http://developer.android.com/guide/developing/devices/emulator.html#emulatornetworking

Sur le thème des "Limites du réseau local", il est dit:

" Selon l'environnement, l'émulateur peut ne pas être en mesure de prendre en charge d'autres protocoles (tels que ICMP, utilisé pour "ping") pourraient ne pas être soutenu. Actuellement, l'émulateur ne prend pas en charge IGMP ou multicast."

Plus d'informations: http://groups.google.com/group/android-developers/browse_thread/thread/8657506be6819297

Il s'agit d'une limitation connue de la pile réseau QEMU en mode utilisateur. Citation du document original: Notez que ping n'est pas pris en charge de manière fiable à Internet car cela nécessiterait des privilèges root. Il signifie que vous ne pouvez envoyer un ping au routeur local (10.0.2.2).

 7
Author: Eugene van der Merwe, 2012-01-29 00:29:49

C'est un simple ping que j'utilise dans l'un des projets:

public static class Ping {
    public String net = "NO_CONNECTION";
    public String host;
    public String ip;
    public int dns = Integer.MAX_VALUE;
    public int cnt = Integer.MAX_VALUE;
}

public static Ping ping(URL url, Context ctx) {
    Ping r = new Ping();
    if (isNetworkConnected(ctx)) {
        r.net = getNetworkType(ctx);
        try {
            String hostAddress;
            long start = System.currentTimeMillis();
            hostAddress = InetAddress.getByName(url.getHost()).getHostAddress();
            long dnsResolved = System.currentTimeMillis();
            Socket socket = new Socket(hostAddress, url.getPort());
            socket.close();
            long probeFinish = System.currentTimeMillis();
            r.dns = (int) (dnsResolved - start);
            r.cnt = (int) (probeFinish - dnsResolved);
            r.host = url.getHost();
            r.ip = hostAddress;
        }
        catch (Exception ex) {
            Timber.e("Unable to ping");
        }
    }
    return r;
}

public static boolean isNetworkConnected(Context context) {
    ConnectivityManager cm =
            (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
}

@Nullable
public static String getNetworkType(Context context) {
    ConnectivityManager cm =
            (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    if (activeNetwork != null) {
        return activeNetwork.getTypeName();
    }
    return null;
}

Utilisation: ping(new URL("https://www.google.com:443/"), this);

Résultat: {"cnt":100,"dns":109,"host":"www.google.com","ip":"212.188.10.114","net":"WIFI"}

 7
Author: Alexander Mayatsky, 2016-06-16 19:51:17

Ping pour le serveur Google ou tout autre serveur

public boolean isConecctedToInternet() {

    Runtime runtime = Runtime.getRuntime();
    try {
        Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
        int     exitValue = ipProcess.waitFor();
        return (exitValue == 0);
    } catch (IOException e)          { e.printStackTrace(); }
    catch (InterruptedException e) { e.printStackTrace(); }
    return false;
}
 4
Author: Pawan Kumar Baranwal, 2016-04-21 19:34:35

Peut-être que les paquets ICMP sont bloqués par votre fournisseur (mobile). Si ce code ne fonctionne pas sur l'émulateur, essayez de renifler via wireshark ou tout autre renifleur et regardez ce qui se passe sur le fil lorsque vous déclenchez la méthode isReachable ().

Vous pouvez également trouver des informations dans le journal de votre appareil.

 1
Author: Luminger, 2010-10-11 11:01:37

C'est ce que j'ai moi-même implémenté, ce qui renvoie la latence moyenne:

/*
Returns the latency to a given server in mili-seconds by issuing a ping command.
system will issue NUMBER_OF_PACKTETS ICMP Echo Request packet each having size of 56 bytes
every second, and returns the avg latency of them.
Returns 0 when there is no connection
 */
public double getLatency(String ipAddress){
    String pingCommand = "/system/bin/ping -c " + NUMBER_OF_PACKTETS + " " + ipAddress;
    String inputLine = "";
    double avgRtt = 0;

    try {
        // execute the command on the environment interface
        Process process = Runtime.getRuntime().exec(pingCommand);
        // gets the input stream to get the output of the executed command
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));

        inputLine = bufferedReader.readLine();
        while ((inputLine != null)) {
            if (inputLine.length() > 0 && inputLine.contains("avg")) {  // when we get to the last line of executed ping command
                break;
            }
            inputLine = bufferedReader.readLine();
        }
    }
    catch (IOException e){
        Log.v(DEBUG_TAG, "getLatency: EXCEPTION");
        e.printStackTrace();
    }

    // Extracting the average round trip time from the inputLine string
    String afterEqual = inputLine.substring(inputLine.indexOf("="), inputLine.length()).trim();
    String afterFirstSlash = afterEqual.substring(afterEqual.indexOf('/') + 1, afterEqual.length()).trim();
    String strAvgRtt = afterFirstSlash.substring(0, afterFirstSlash.indexOf('/'));
    avgRtt = Double.valueOf(strAvgRtt);

    return avgRtt;
}
 1
Author: sorry_I_wont, 2016-01-20 22:53:39

Cela a fonctionné pour moi, pas de racine, Android 6.0, Android Studio, Acatel U3:

    private boolean Ping(String IP){
    System.out.println("executeCommand");
    Runtime runtime = Runtime.getRuntime();
    try
    {
        Process  mIpAddrProcess = runtime.exec("/system/bin/ping -c 1 " + IP);
        int mExitValue = mIpAddrProcess.waitFor();
        System.out.println(" mExitValue "+mExitValue);
        if(mExitValue==0){
            return true;
        }else{
            return false;
        }
    }
    catch (InterruptedException ignore)
    {
        ignore.printStackTrace();
        System.out.println(" Exception:"+ignore);
    }
    catch (IOException e)
    {
        e.printStackTrace();
        System.out.println(" Exception:"+e);
    }
    return false;
}
 0
Author: Ramon Black, 2018-07-06 16:05:18

Utilisez ce code: cette méthode fonctionne sur 4.3+ et aussi pour les versions ci-dessous.

   try {

         Process process = null;

        if(Build.VERSION.SDK_INT <= 16) {
            // shiny APIS 
               process = Runtime.getRuntime().exec(
                    "/system/bin/ping -w 1 -c 1 " + url);


        } 
        else 
        {

                   process = new ProcessBuilder()
                 .command("/system/bin/ping", url)
                 .redirectErrorStream(true)
                 .start();

            }



        BufferedReader reader = new BufferedReader(new InputStreamReader(
                process.getInputStream()));

        StringBuffer output = new StringBuffer();
        String temp;

        while ( (temp = reader.readLine()) != null)//.read(buffer)) > 0)
        {
            output.append(temp);
            count++;
        }

        reader.close();


        if(count > 0)
            str = output.toString();

        process.destroy();
     } catch (IOException e) {
         e.printStackTrace();
    }

    Log.i("PING Count", ""+count);
    Log.i("PING String", str);
 -1
Author: Ahmad Arslan, 2014-02-12 07:13:48