我已经编写了这个代码用于在端口6789上ping类c ip地址,当我点击一个名为PING的按钮时线程启动,它将检索所有打开端口6789的IP地址...但我需要的是每次刷新(重新ping),比方说5秒,并添加最近加入的ips(如果存在)并省略离开端口的ips。 我调试并搜索了几个小时,但没有希望!
提前致谢:DD
Thread pingo = new Thread(new Runnable() {
public void run() {
if (readableNetmask.equals("255.255.255.0")) {
for (int i = 2; i <= 254; i++) {
String ip_address = readableIPAddress;
String oct1 = "", oct2 = "", oct3 = "", oct4 = "";
StringTokenizer stok = new StringTokenizer(
ip_address, ".");
while (stok.hasMoreTokens()) {
oct1 = stok.nextToken();
oct2 = stok.nextToken();
oct3 = stok.nextToken();
oct4 = stok.nextToken();
}
to_ping_ip = oct1 + "." + oct2 + "." + oct3 + "."
+ String.valueOf(i);
if (pingAddress(to_ping_ip, 6789)) {
handler.post(new UpdateIPListViewRunnable());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// ips_List.add(to_ping_ip);
}
}
}
}
});
pingo.start();
PingAddress()函数:
public boolean pingAddress(String ip, int port) {
Socket socket = new Socket();
try {
socket.connect(new InetSocketAddress(ip, port), 200);
socket.close();
} catch (IOException e) {
return false;
}
return true;
}
列出地址的位置:
static public class UpdateIPListViewRunnable implements Runnable {
public void run() {
arrayAdapter.add(to_ping_ip);
arrayAdapter.notifyDataSetChanged();
}
}
答案 0 :(得分:1)
只需添加一个睡眠时间为5秒的循环,如此处所示。我想您已经可以将ping的新结果集成到先前捕获的数据中。
Thread pingo = new Thread(new Runnable() {
public void run() {
while (true) {
if (readableNetmask.equals("255.255.255.0")) {
// keep the above logic
}
// delay 5 seconds
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
break;
}
}
}
});
pingo.start();
答案 1 :(得分:0)
这应该对你有帮助。
private void doPing() {
if (readableNetmask.equals("255.255.255.0")) {
// Your logic
}
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
doPing();
}
}, 5*1000);
}