如何使用 java(线程)对一系列 IP 地址 ping snmp 设备?
我需要创建一个线程池,以使用 java 语言同时 ping 一系列 IP 地址。
请帮帮我。
已编辑1
如果创建了很多线程,那么我们是否必须显式调用 stop() 方法来停止线程?或者会被照顾吗?
I need to create a thread pool to ping a range of ip addresses simultaneously using java language.
Please help me out.
Edited 1
If there are lots of thread created, then whether we have to call stop() method explicitly to stop the thread? or will it be taken care?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是 pingig 子任务的实现。使用引用的有效负载创建线程池和线程不应该太复杂。
编辑
如果您可以修改这些设备上的客户端代码,我建议使用自定义协议而不是使用回显端口 - 类似于心跳,您经常向客户端发送一条小消息(在标准或不同的端口)并期望在规定的时间内得到答复。
编辑 2
对于线程基础知识,我强烈建议您查看 Java 教程。首先:实现一个类似
public class PingThread extends Thread
的类,并将链接中的代码放置在 run 方法的while(true) {...}
循环内。使用 Thread.sleep() 在同一循环中的 ping 之间添加等待时间。如果您确实需要ThreadGroup,请重写构造函数
Thread(ThredGroup group, String name)
,以便可以在您指定的组中创建PingThread。您可能想要实现一个开关来停止 PingThread(几乎每个 Java 教程都应该涵盖),
Here's an implementation of the pingig subtask. Creating a thread pool and threads with the referenced payload shouldn't be too complicated.
Edit
If you can modify the client code on these devices, I suggest a custom protocol instead of using the echo port - something like a heartbeat where you frequently send a small message to the client (on the standard or a different port) and expect an answer within a defined time.
Edit 2
For the thread basics, I really suggest looking at a Java tutorial. To start with: implement a class like
public class PingThread extends Thread
and place the code from the link inside awhile(true) {...}
loop in the run method. UseThread.sleep()
to add a wait time between to pings in the the same loop.If you really need a ThreadGroup, override the constructor
Thread(ThredGroup group, String name)
so that a PingThread can be created in your specified group.You may want to implement a switch to stop a PingThread (should be covered by almost every Java tutorial),
默认情况下,Java 没有 ICMP 实现,因此无法使用标准库从 Java ping 主机。您的其他选择是寻找 Java ICMP 实现(我不知道是否存在),或者从 Java 调用系统上的“ping”可执行文件并解析输出。
编辑:Andreas_D 的链接表明 InetAddress.isReachable() 使用 ICMP 回显请求来 ping 主机,因此这就是实现 ping 的方法。
您可以从该页面获取 ReachableTest 的代码,并将 ReachableTest 类更改为 Runnable,然后您可以在其自己的线程中运行该类,或者使用 java.util.concurrent 中的执行程序服务运行:
Java has no implementation of ICMP by default, so it's not possible to ping a host from Java with the standard library. Your other options are to look for a Java ICMP implementation (I don't know if one exists), or to call the 'ping' executable on your system from Java and parse the output.
Edit: Andreas_D's link indicates that InetAddress.isReachable() uses an ICMP echo request to ping a host, so that's how you can implement the ping.
You can take the code for the ReachableTest from that page and change the ReachableTest class into a Runnable which you can then run in its own thread or by using the executor service from java.util.concurrent: