0

我已经编写了这段代码,用于在端口 6789 上 ping c 类 IP 地址,当我单击一个名为 PING 的按钮时线程开始,它将检索所有打开端口 6789 的 IP 地址......但我需要的是刷新(重新 ping)每,假设 5 秒,并添加最近加入的 ip(如果存在)并省略离开端口的 ip。我调试并搜索了几个小时但没有希望!

提前感谢: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();
    }
}
4

2 回答 2

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();
于 2013-05-01T10:59:40.330 回答
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);
}
于 2013-05-01T11:12:27.937 回答