gpt4 book ai didi

java - Android ICMP ping

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:01:03 24 4
gpt4 key购买 nike

有没有办法 ping 主机(标准 Android 或通过 NDK 实现),并获取有关响应的详细信息? (时间、ttl、丢失的包裹等。)我正在考虑一些具有此功能但找不到的开源应用程序......

谢谢

最佳答案

Afaik,发送 ICMP ECHO 请求需要 root(即需要 setuid 的应用程序)——而这在“stock”Android 中目前是不可能的(该死的) ,甚至 Android 中的 InetAddress#isReachable() 方法也是一个 joke,根据规范不工作)。

一个使用/usr/bin/ping & Process 的非常基本的示例 - 使用 AsyncTask 读取 ping 结果:

public class PingActivity extends Activity {
PingTask mTask;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}

@Override
protected void onResume() {
super.onResume();
mTask = new PingTask();
// Ping the host "android.com"
mTask.execute("android.com");
}

@Override
protected void onPause() {
super.onPause();
mTask.stop();
}

class PingTask extends AsyncTask<String, Void, Void> {
PipedOutputStream mPOut;
PipedInputStream mPIn;
LineNumberReader mReader;
Process mProcess;
TextView mText = (TextView) findViewById(R.id.text);
@Override
protected void onPreExecute() {
mPOut = new PipedOutputStream();
try {
mPIn = new PipedInputStream(mPOut);
mReader = new LineNumberReader(new InputStreamReader(mPIn));
} catch (IOException e) {
cancel(true);
}

}

public void stop() {
Process p = mProcess;
if (p != null) {
p.destroy();
}
cancel(true);
}

@Override
protected Void doInBackground(String... params) {
try {
mProcess = new ProcessBuilder()
.command("/system/bin/ping", params[0])
.redirectErrorStream(true)
.start();

try {
InputStream in = mProcess.getInputStream();
OutputStream out = mProcess.getOutputStream();
byte[] buffer = new byte[1024];
int count;

// in -> buffer -> mPOut -> mReader -> 1 line of ping information to parse
while ((count = in.read(buffer)) != -1) {
mPOut.write(buffer, 0, count);
publishProgress();
}
out.close();
in.close();
mPOut.close();
mPIn.close();
} finally {
mProcess.destroy();
mProcess = null;
}
} catch (IOException e) {
}
return null;
}
@Override
protected void onProgressUpdate(Void... values) {
try {
// Is a line ready to read from the "ping" command?
while (mReader.ready()) {
// This just displays the output, you should typically parse it I guess.
mText.setText(mReader.readLine());
}
} catch (IOException t) {
}
}
}
}

关于java - Android ICMP ping,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9062182/

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