Java快速检查网络连接

Ben*_*ole 11 java networking java-5

我的问题相当简单.如果网络连接丢失,我的程序需要立即通知.我正在使用Java 5,所以我无法使用NetworkInterface的非常方便的功能.

目前我有两种不同的检查网络连接的方法:(
try ..catches removed)

方法一:

URL url = new URL("http://www.google.com");
HttpURLConnection urlConnect = (HttpURLConnection) url.openConnection();
// trying to retrieve data from the source. If offline, this line will fail:
Object objData = urlConnect.getContent();
return true;
Run Code Online (Sandbox Code Playgroud)

方法2:

Socket socket = new Socket("www.google.com", 80);
netAccess = socket.isConnected();
socket.close();
return netAccess;
Run Code Online (Sandbox Code Playgroud)

但是,这两种方法都会阻塞,直到达到超时,然后才返回false.我需要一个立即返回的方法,但与Java 5兼容.

谢谢!

编辑:我忘了提到我的程序依赖于IP地址,而不是DNS名称.因此在解析主机时检查错误...

第二次编辑:

使用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;
                }
            }
        }
Run Code Online (Sandbox Code Playgroud)

Ali*_*Ali 10

来自JGuru

从Java 5开始,InetAddress类中有一个isReachable()方法.您可以指定超时或要使用的NetworkInterface.有关ping使用的基础Internet控制消息协议(ICMP)的详细信息,请参阅RFC 792(http://www.faqs.org/rfcs/rfc792.html).

来自Java2s的用法

  int timeout = 2000;
  InetAddress[] addresses = InetAddress.getAllByName("www.google.com");
  for (InetAddress address : addresses) {
    if (address.isReachable(timeout))
      System.out.printf("%s is reachable%n", address);
    else
      System.out.printf("%s could not be contacted%n", address);
  }
Run Code Online (Sandbox Code Playgroud)

如果要避免阻塞,请在java.nio包中使用Java NIO(非阻塞IO)

String host = ...; 
InetSocketAddress socketAddress = new InetSocketAddress(host, 80); 
channel = SocketChannel.open(); 
channel.configureBlocking(false); 
channel.connect(socketAddress);
Run Code Online (Sandbox Code Playgroud)