What is the quickest way to detect an unreachable host in Java?

后端 未结 6 929
野性不改
野性不改 2021-02-08 01:38

I would like the fastest and most accurate function boolean isReachable(String host, int port) that passes the following JUnit tests under the conditions below. Tim

相关标签:
6条回答
  • 2021-02-08 02:15

    The rate determining step for host availability is not within your own code, but in the netlag. You must wait for the host to respond, and this can take time. If your program blocks while waiting for a response it could be a problem. I got around this by creating each host as an object, each with its own threaded method for checking availability. In my own situation I have 40 hosts I keep track of. My main program loops through an array of 40 machine objects once every 20 seconds, calling the appropriate method on each to check availability. Since each machine object spawns its own thread to do this, all 40 machines are interrogated concurrently and the (up to 500ms) response time for each isn't a problem.

    0 讨论(0)
  • 2021-02-08 02:16

    If you need to do this with a seriously large number of hosts in a very brief period of time, I'd consider using a tool like fping instead- shell out to exec it and parse the output when it comes back. fping runs a large number of parallel queries at once, so you could theoretically check a few thousand hosts in a minute (I think the limit is 4096?)

    0 讨论(0)
  • 2021-02-08 02:21

    My most recent solution depends using a TimedSocket (source code) with 3000ms timeout while performing a connect.

    Timings:

    • 1406ms : testLocalHost()
    • 5280ms : testLAN()

    Can't even get these to work properly:

    • testNoDNS()
    • testHaveDNS()
    0 讨论(0)
  • 2021-02-08 02:21

    Not sure how practical this is.

    How about doing the equivalent of traceroute(tracert on windows) and once you get a success, you can proceed.

    In corporate networks, I've seen ICMP(ping) blocked by admins BUT usually, tracert still works. If you can figure out a quick way to do what tracert does, that should do the trick ?

    Good luck!

    0 讨论(0)
  • 2021-02-08 02:24

    If you want to test whether you can connect to a web server you could also create a URL based on the host name and the port number and use that to create a URLConnection checking the result (including exceptions) of the connect method should tell you whether the webserver is reachable.

    0 讨论(0)
  • 2021-02-08 02:26

    Firstly you need to recognise that you have potentially conflicting requirements; IP sockets are not time deterministic. The quickest you can ever detect unreachability is after your elapsed timeout. You can only detect reachability quicker.

    Assuming reachability/isReachable is your real objective, you should just use a straightforward non-blocking socket IO as shown in the Java Ping simulator, the example connects to the time service but would work equally well on 8080.

    0 讨论(0)
提交回复
热议问题