簡體   English   中英

如何使用nslookup檢查Java中的Internet可用性?

[英]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檢查連接可用性。

請提出最佳方法。 謝謝

這個問題有幾個陷阱:

  1. 從最具體的一個開始-連接到localhost :即使您的計算機沒有網卡,它也可以在環回接口上解析localhost並連接到自身(如果有開放端口)。
  2. 您的DNS可能已關閉/配置錯誤,因此您無法解析example.com但可以通過IP( 93.184.216.34 )連接到它-這是否意味着“互聯網不可用”?
  3. 您公司中的防火牆可能阻止了某些站點,但允許其他站點-是不是“互聯網不可用”?
  4. example.com的服務器已關閉,而世界上所有其他站點均正常運行。 這是否意味着“ Internet可用”?
  5. 您公司的防火牆可能只允許在標准端口80和443上進行HTTP連接,而不允許其他端口。 因此, 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM