views:

289

answers:

3

Hi All,

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?

+1  A: 

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 a while(true) {...} loop in the run method. Use Thread.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),

Andreas_D
It doesn't talk about thread concept. Only the reachable test and ping is taken care.
MalarN
A: 

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:

public class ReachableTest implements Runnable {
  private String host;

  public ReachableTest(String host) {
    this.host = host;
  }

  public void run() {
    try {
      InetAddress address = InetAddress.getByName(host);
      System.out.println("Name: " + address.getHostName());
      System.out.println("Addr: " + address.getHostAddress());
      System.out.println("Reach: " + address.isReachable(3000));
    }
    catch (UnknownHostException e) {
      System.err.println("Unable to lookup " + host);
    }
    catch (IOException e) {
      System.err.println("Unable to reach " + host);
    }
  }
}
liwp
A: 

Hi, why the isReachable() methode is not reconized in my code ??

Bilel