Pinging External IPs from Java Android
In Java Android development, it is possible to ping both local and external IP addresses. However, if you're encountering issues when trying to ping external servers, here's a troubleshooting guide:
Code Analysis:
Your code attempts to ping an IP address by using the InetAddress.isReachable() method. This method only tests local IP addresses. To enable pinging of external servers, you need to use a different approach.
Solution: Using Native Commands
The provided code in the answer uses native commands to execute a ping operation. This approach allows you to ping any IP address, both local and external. Here's an explanation of the code:
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; }
Ensure that you have the necessary permissions in your AndroidManifest.xml file to access the internet before using this code.
Additional Considerations:
The above is the detailed content of How to Ping External IPs from Java Android?. For more information, please follow other related articles on the PHP Chinese website!