简体   繁体   中英

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

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM