如何在安卓设备上进行ICMP Ping

15

我需要在我的Android设备上对主机进行ICMP Ping。我需要测量往返时间。我熟练掌握Android和Java,只是不知道使用哪个库。 我该怎么做? 是否可以通过3G,Edge实现?


为什么需要测量ICMP往返时间? - dbasnett
4个回答

15

是的,只要有连接,您可以使用3G、Edge、无线等方式进行ping。唯一的限制在于模拟器中,请参见此处: http://groups.google.com/group/android-developers/browse_thread/thread/8657506be6819297

这是我的ping功能:

package com.namespace.router.api;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import android.util.Log;

public class Network {

    private static final String TAG = "Network.java";   

    public static String pingError = null;

    /**
     * Ping a host and return an int value of 0 or 1 or 2 0=success, 1=fail, 2=error
     * 
     * Does not work in Android emulator and also delay by '1' second if host not pingable
     * In the Android emulator only ping to 127.0.0.1 works
     * 
     * @param String host in dotted IP address format
     * @return
     * @throws IOException
     * @throws InterruptedException
     */
    public static int pingHost(String host) throws IOException, InterruptedException {
        Runtime runtime = Runtime.getRuntime();
        Process proc = runtime.exec("ping -c 1 " + host);
        proc.waitFor();     
        int exit = proc.exitValue();
        return exit;
    }

    public static String ping(String host) throws IOException, InterruptedException {
        StringBuffer echo = new StringBuffer();
        Runtime runtime = Runtime.getRuntime();
        Log.v(TAG, "About to ping using runtime.exec");
        Process proc = runtime.exec("ping -c 1 " + host);
        proc.waitFor();
        int exit = proc.exitValue();
        if (exit == 0) {
            InputStreamReader reader = new InputStreamReader(proc.getInputStream());
            BufferedReader buffer = new BufferedReader(reader);
            String line = "";
            while ((line = buffer.readLine()) != null) {
                echo.append(line + "\n");
            }           
            return getPingStats(echo.toString());   
        } else if (exit == 1) {
            pingError = "failed, exit = 1";
            return null;            
        } else {
            pingError = "error, exit = 2";
            return null;    
        }       
    }

    /**
     * getPingStats interprets the text result of a Linux ping command
     * 
     * Set pingError on error and return null
     * 
     * http://en.wikipedia.org/wiki/Ping
     * 
     * PING 127.0.0.1 (127.0.0.1) 56(84) bytes of data.
     * 64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.251 ms
     * 64 bytes from 127.0.0.1: icmp_seq=2 ttl=64 time=0.294 ms
     * 64 bytes from 127.0.0.1: icmp_seq=3 ttl=64 time=0.295 ms
     * 64 bytes from 127.0.0.1: icmp_seq=4 ttl=64 time=0.300 ms
     *
     * --- 127.0.0.1 ping statistics ---
     * 4 packets transmitted, 4 received, 0% packet loss, time 0ms
     * rtt min/avg/max/mdev = 0.251/0.285/0.300/0.019 ms
     * 
     * PING 192.168.0.2 (192.168.0.2) 56(84) bytes of data.
     * 
     * --- 192.168.0.2 ping statistics ---
     * 1 packets transmitted, 0 received, 100% packet loss, time 0ms
     *
     * # ping 321321.
     * ping: unknown host 321321.
     * 
     * 1. Check if output contains 0% packet loss : Branch to success -> Get stats
     * 2. Check if output contains 100% packet loss : Branch to fail -> No stats
     * 3. Check if output contains 25% packet loss : Branch to partial success -> Get stats
     * 4. Check if output contains "unknown host"
     * 
     * @param s
     */
    public static String getPingStats(String s) {
        if (s.contains("0% packet loss")) {
            int start = s.indexOf("/mdev = ");
            int end = s.indexOf(" ms\n", start);
            s = s.substring(start + 8, end);            
            String stats[] = s.split("/");
            return stats[2];
        } else if (s.contains("100% packet loss")) {
            pingError = "100% packet loss";
            return null;            
        } else if (s.contains("% packet loss")) {
            pingError = "partial packet loss";
            return null;
        } else if (s.contains("unknown host")) {
            pingError = "unknown host";
            return null;
        } else {
            pingError = "unknown error in getPingStats";
            return null;
        }       
    }
}

2
ping(8.8.8.8) 总是失败。 - danarj
无法在三星S3 4.2.2和其他4.2.2设备上运行!! - Punit Sharma
请注意字符串匹配:".contains"中的"100%数据包丢失"和"0%数据包丢失"是相同的。 - Callum Wilson
仿真器不是唯一的限制,还有很多设备不支持ping命令。 - Shayan_Aryan
@Shayan_Aryan 你有没有找到其他的替代方案? - GiridharaSPK
@GiridharaSPK,不幸的是,没有像ping一样好的解决方案。我不得不向服务器发送HTTP请求,而不是ping它的IP地址。还有一些本地库实现了ping功能,你可以使用它们,但需要使用Android NDK。 - Shayan_Aryan

6

您可能希望使用isReachable - 更多细节请参见Android文档。但是,显然有些网络会阻止ICMP。您可以在此处阅读更多关于此问题的信息。


1

您可以使用可在此处获得的终端模拟器的开源代码。

构建库文件(使用cygwinandroid-ndk),然后使用它。


-1

从socket(2)手册中可以看到,设备中的ping访问受/proc/sys/net/ipv4/ping_group_range文件内容的限制。

$ cat /proc/sys/net/ipv4/ping_group_range

默认情况下为"1 0",这意味着没有人(甚至是root)可以创建ping套接字。将其设置为"100 100"将授予单个组权限(要么使/sbin/ping g+s并由该组拥有,要么授予权限给"netadmins"组),"0 4294967295"将使其对全世界开放,"100 4294967295"将使其对用户开放,但不包括守护程序。

因此,任何具有除"0 4294967295"之外的其他值的设备都无法从Android Java应用程序中访问。

在模拟器中,您可以通过重置来测试此功能

sysctl -w net.ipv4.ping_group_range="0 0" // 到某个范围内


这怎么回答了原来的问题呢? - Stefan Becker

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接