gpt4 book ai didi

java - 如何从 Java Android ping 外部 IP

转载 作者:IT老高 更新时间:2023-10-28 20:29:03 24 4
gpt4 key购买 nike

我正在为 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 (Google DNS) -> Time Out

我也在 Manifest XML 中添加了以下行:

<uses-permission android:name="android.permission.INTERNET"></uses-permission>

谁能建议我哪里做错了?

最佳答案

我尝试了以下代码,这对我有用。

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;
}

关于java - 如何从 Java Android ping 外部 IP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3905358/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com