2015年10月5日 星期一

「Android」InetAddress.isReachable

最近在工作上需要用到PING的功能,查詢了一下

InetAddress.isReachable(Timeout)

這個是JAVA去實作ICMP的功能,後面的Timeout

指的是即使對方有應PING,但回應的時間超過Timeout

這個函式依然會回傳false.


但是在Android上使用,發現不太對勁,上網爬了文

明明存在的IP確回傳false, 但在try一次,卻總是回傳true,

面對沒人用的IP,retry卻回傳TRUE 。





seems that isReachable() never worked well on Android b/c it tries to use ICMP, that usually needs a root privileges, and then it tries to establish connection to port 7, that's usually have no running services on modern systems.
you'd better check connectivity with establishing TCP connection to ports you know should be open.
來源:

http://stackoverflow.com/questions/16441620/android-inetaddress-getbynameip-isreachabletimeout-always-returns-false



he best way to test the availablity of any resource is to try to use it. The best way to detect whether any specific IP is accessible is to try to connect to it to do what you need to do. Don't use isReachable() as a prior test at all. It doesn't test the same things.

來源:
http://stackoverflow.com/questions/16441620/android-inetaddress-getbynameip-isreachabletimeout-always-returns-false


InetAddress.isReachable(int) returns true for unreachable addresses.

http://bugs.java.com/bugdatabase/view_bug.do?bug_id=4921816



最後改用了下面這一個方法使用PING,才比較正常。


Process p1 = java.lang.Runtime.getRuntime().exec("ping -c 1 www.google.com");
int returnVal = p1.waitFor();
boolean reachable = (returnVal==0);

參考來源:

http://shovachu-coding.blogspot.tw/2014/03/androidping.html

沒有留言:

張貼留言