Alternatives to calling ping executable from Java on Android
我使用以下代码来调用android设备ping命令:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | public static String pingServer() { PingResult result = new PingResult(); String jsonString = null; try { String command ="ping -c 3 192.168.8.185"; Process p = Runtime.getRuntime().exec(command); int status = p.waitFor(); InputStream input = p.getInputStream(); BufferedReader in = new BufferedReader(new InputStreamReader(input)); StringBuffer buffer = new StringBuffer(); String line =""; while ((line = in.readLine()) != null) { buffer.append(line); buffer.append(" "); } String bufferStr = buffer.toString(); System.out.println(bufferStr); } catch (Exception e) { System.out.println("---------------exception-----------ping"); System.out.println(e.getMessage()); // e.printStackTrace(); } } |
BufferStr始终获取最后一行数据。
传输3个包,3个接收,0%丢包,时间2000ms
细节结果可以得到。
使用InetAddress.isReachable可能更简单,更容易:
1 2 | if (InetAddress.getByName("192.168.8.185").isReachable(6000)) ... |