可以ping通,而InetAddress isReachable卻返回false

封巍發表於2017-01-05

程式:

package xxx.xxx;


import org.junit.Test;
import java.io.IOException;
import java.net.InetAddress;

public class InetAddressTest {

    @Test
    public void testIsReachable() {
        try {
            System.out.println("testing................................");
            System.out.println(InetAddress.getByName("xxx.xxx.xxx.xxx").isReachable(10));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


原因:

檢視啟動程式的賬戶為user,非root,而isReachable使用icmp實現此功能,需要root許可權


參考:

http://stackoverflow.com/questions/4779367/problem-with-isreachable-in-inetaddress-class

(read the javadoc, it requires such privileges. Basically to use ICMP (raw socket), it does take 'root'. And if you ask why ping from bash doesn't, actually it does need as well. Do that ls -l /bin/ping)

相關文章