Checking Host Reachability/Availability in Android

前端 未结 4 615
再見小時候
再見小時候 2020-12-07 20:53

Ive been trying to do what i thought would be a simple reachability of host test at the beginning of my apps internet ventures, but documentation isnt helping and neither ar

4条回答
  •  春和景丽
    2020-12-07 21:40

    Try this one:

    boolean reachable = false;
    
    try {
        reachable = InetAddress.getByName("www.example.com").isReachable(2000);
    } catch (IOException e) {
        e.printStackTrace();
        reachable = false;
    }
    
    if (reachable) { 
        // do your work here 
    } 
    

    But this could fail even if the web server is up and running perfectly because of the way how isReachable(int timeout) is implemented:

    Test whether that address is reachable. Best effort is made by the implementation to try to reach the host, but firewalls and server configuration may block requests resulting in a unreachable status while some specific ports may be accessible. A typical implementation will use ICMP ECHO REQUESTs if the privilege can be obtained, otherwise it will try to establish a TCP connection on port 7 (Echo) of the destination host.

提交回复
热议问题