InetAddress byName = InetAddress.getByName("173.39.161.140");
System.out.println(byName);
System.out.println(byName.isReachable(1000));
为什么isReachable
会返回false
?我可以ping通IP地址。
发布于 2015-12-12 01:02:06
我来这里是为了得到这个问题的答案,但我对任何一个答案都不满意,因为我正在寻找一个独立于平台的解决方案。下面是我编写的代码,它是独立于平台的,但需要关于另一台机器上任何开放端口的信息(我们大部分时间都有)。
private static boolean isReachable(String addr, int openPort, int timeOutMillis) {
// Any Open port on other machine
// openPort = 22 - ssh, 80 or 443 - webserver, 25 - mailserver etc.
try {
try (Socket soc = new Socket()) {
soc.connect(new InetSocketAddress(addr, openPort), timeOutMillis);
}
return true;
} catch (IOException ex) {
return false;
}
}
发布于 2013-07-27 00:48:56
如果您只想检查它是否连接到互联网使用此方法,它返回true,如果互联网已连接,如果您使用的是您试图通过程序连接的网站地址,则更可取。
public static boolean isInternetReachable()
{
try {
//make a URL to a known source
URL url = new URL("http://www.google.com");
//open a connection to that source
HttpURLConnection urlConnect = (HttpURLConnection)url.openConnection();
//trying to retrieve data from the source. If there
//is no connection, this line will fail
Object objData = urlConnect.getContent();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
发布于 2016-09-29 05:12:10
我不确定当最初的问题在2012年被问到的时候是什么状态。
按照现在的情况,ping将以root身份执行。通过ping可执行文件的授权,您将看到+s标志和属于root的进程,这意味着它将以root身份运行。在ping所在的位置运行ls -liat,您应该会看到它。
因此,如果您以根用户身份运行InetAddress.getByName("www.google.com").isReacheable(5000),它应该返回true。
您需要对ICMP (ping使用的协议)使用的原始套接字进行适当的授权。
InetAddress.getByName与ping一样可靠,但您需要对进程具有适当的权限才能使其正常运行。
https://stackoverflow.com/questions/9922543
复制相似问题