Salman Raza
Salman Raza

Reputation: 1715

How do I count the number of times I ping a host in JSP?

My code is here from which I get result either true or false that weather it ping to the host I mention in it or not,

  try
  {
      InetAddress address = InetAddress.getByName("192.168.1.125");
      boolean reachable=address.isReachable(10000));
      out.print(PingHost.DrawTable());
      out.print("Is host reachable? " + reachable);
  }
  catch(Exception e)
  {
      out.print(e.printStackTrace());
  }

I want to count the no of times it try to ping the host if it is not ping success fully fro the first time and the max no of count for ping would be 10

Hopes for your suggestions

Thanks in Advance

Upvotes: 3

Views: 585

Answers (3)

Deepak Bala
Deepak Bala

Reputation: 11185

I would first question why this code needs to reside in a JSP. A request to this JSP will take forever to get back to you if the host is unreachable. Any solution that uses a member variable to track the count will also be problematic since it will run into concurrency issues.

You are better off writing LaceySnr's code on a servlet and spawning that code on a separate thread.

Upvotes: 0

mohdajami
mohdajami

Reputation: 9680

final static int MAX_PINGS = 10;
final static int TIMEOUT= 10000;
int countFailed = 0;

for (int i=0; i<MAX_PINGS; i++){
    if (address.isReachable(TIMEOUT)){
         System.out.println("Pinged successfully");
         break;
    }else{
         countFailed++;
    }
 }

Note: giving 10000ms (10 seconds) as timeout is too much. I suggest it should be around 1000 ms.

Upvotes: 5

Matt Lacey
Matt Lacey

Reputation: 8255

Assuming that address.isReachable(10000)) is doing the ping, and returns true or false, then you want something like this:

int counter = 0;

do
{
    counter ++; 
    if(address.isReachable(10000))
    {
        break;
    }
}
while (counter < 10)

// now counter contains the number of attempts

I think you'd do well to find a good book on programming, to come up with a solution similar to this should not be something you need to ask about.

Upvotes: 3

Related Questions