3

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

Matt Lacey
  • 8,227
  • 35
  • 58
Salman Raza
  • 1,635
  • 6
  • 18
  • 18
  • Where is `reachable` defined and where is it set? Also, I've fixed the formatting but you have some other issues here, for instance, either the `;` on the second `if` statement an accident? If not, then you don't need the `if` statement. – Matt Lacey Jan 05 '12 at 06:39
  • i have EDITED THE CODE NOW ITS FINE – Salman Raza Jan 05 '12 at 06:49
  • I thought that was probably want you intended, always best to make sure the code is accurate in order to get the best response! Hope what I answered makes sense. – Matt Lacey Jan 05 '12 at 06:53

3 Answers3

5
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.

mohdajami
  • 9,604
  • 3
  • 32
  • 53
3

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.

Matt Lacey
  • 8,227
  • 35
  • 58
0

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.

Community
  • 1
  • 1
Deepak Bala
  • 11,095
  • 2
  • 38
  • 49