In Android development, it is often necessary to verify network connectivity by sending ping requests to both local and external IP addresses. While pinging local IPs is straightforward, extending this functionality to external servers can present challenges.
One common approach is to use the Java InetAddress class to perform ping operations. However, this method is restricted to local IP addresses. To overcome this limitation, an alternate solution is required.
The proposed solution involves utilizing the Android Runtime class and the /system/bin/ping command. Here's how you can implement it:
<br>private boolean executeCommand(){</p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false"> 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; }
By executing the /system/bin/ping command within the Java code, you can successfully send ping requests to external IP addresses. Remember to include the necessary permissions in the AndroidManifest.xml file, specifically the android.permission.INTERNET permission.
The above is the detailed content of How to Ping External IP Addresses from Android Java Applications?. For more information, please follow other related articles on the PHP Chinese website!