目前我正在使用 URL()
public boolean isInternetAvailable(){
try {
URL url = new URL("http://www.google.com");
HttpURLConnection urlConnect = (HttpURLConnection)url.openConnection();
urlConnect.setConnectTimeout(5000);
Object objData = urlConnect.getContent();
return true;
} catch (Exception e) {}
return false;
}
但是在需求中,我们不想使用任何URL。如果连接可用,我们希望 ping localhost,否则返回 true。
对于 nslookup 我正在使用
try
{
InetAddress inetAddress = InetAddress.getByName("localhost");
System.out.println("Host: " +inetAddress.getHostName());
System.out.println("IP Address: " +inetAddress.getHostAddress());
System.out.println("IP Address: " +inetAddress.isSiteLocalAddress());
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
但我不明白如何使用 nslookup 检查连接可用性。
请建议最佳方法。谢谢
最佳答案
这个问题有几个问题:
- 从最具体的一个开始 - 连接到
localhost
:即使您的计算机没有网卡,它也能够解析 loopback interface 上的 localhost并连接到自身(如果有开放端口)。 - 您的 DNS 可能已关闭/配置错误,因此您无法解析
example.com
,但您可以通过 IP (93.184.216.34
) 连接到它 - 这是否意味着比“互联网不可用”? - 您公司的防火墙可能会阻止某些网站,但允许其他网站 - 这是否意味着“互联网不可用”?
example.com
的服务器已关闭,而世界上所有其他网站都工作正常。这是否意味着“互联网可用”?- 您公司的防火墙可能只允许标准端口 80 和 443 上的 HTTP 连接,而不允许其他端口。因此,
http://example.com
连接,但http://example.com:12345
未连接。这是否意味着“互联网可用”?
因此,您实际上可以问的唯一问题是您是否可以使用其域名和/或其 IP 地址连接到特定端口上的特定主机。
关于java - 如何使用 nslookup 检查 Java 中的互联网可用性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34272325/