如何从Java Android中ping外部IP我正在为Android 2.2开发一个Ping应用程序。我尝试我的代码,它的工作原理,但只在本地IP,这是我的问题,我想ping外部服务器。这是我的代码: 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) - >超时我还将以下行放在Manifest XML上:<uses-permission android:name="android.permission.INTERNET"></uses-permission>任何人都可以建议我在哪里做错了吗?
3 回答
江户川乱折腾
TA贡献1851条经验 获得超5个赞
我尝试了以下代码,这对我有用。
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;
}添加回答
举报
0/150
提交
取消
