[英]How to check Internet availability in Java using nslookup?
目前,我正在使用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
:即使您的計算機沒有網卡,它也可以在環回接口上解析localhost並連接到自身(如果有開放端口)。 example.com
但可以通過IP( 93.184.216.34
)連接到它-這是否意味着“互聯網不可用”? example.com
的服務器已關閉,而世界上所有其他站點均正常運行。 這是否意味着“ Internet可用”? http://example.com
連接,但http://example.com:12345
不會。 這是否意味着“ Internet可用”? 因此,您真正要問的唯一問題是,是否可以使用其域名和/或IP地址連接到特定端口上的特定主機。
使用NetworkInterface找出最終解決方案:
Enumeration<NetworkInterface> eni = NetworkInterface.getNetworkInterfaces();
while(eni.hasMoreElements()) {
Enumeration<InetAddress> eia = eni.nextElement().getInetAddresses();
while(eia.hasMoreElements()) {
InetAddress ia = eia.nextElement();
if (!ia.isAnyLocalAddress() && !ia.isLoopbackAddress() && !ia.isSiteLocalAddress()) {
if (!ia.getHostName().equals(ia.getHostAddress()))
return true;
}
}
}
我從這里得到了解決方案: -Java快速檢查網絡連接
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.