Java Quickly check for network connection

前端 未结 4 1968
暗喜
暗喜 2021-02-20 08:14

My issue is fairly straightforward. My program requires immediate notification if a network connection is lost. I\'m using Java 5, so I\'m unable to use the very handy feature

4条回答
  •  北恋
    北恋 (楼主)
    2021-02-20 08:49

    From JGuru

    Starting with Java 5, there is an isReachable() method in the InetAddress class. You can specify either a timeout or the NetworkInterface to use. For more information on the underlying Internet Control Message Protocol (ICMP) used by ping, see RFC 792 (http://www.faqs.org/rfcs/rfc792.html).

    Usage from 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);
      }
    

    If you want to avoid blocking use Java NIO (Non-blocking IO) in the java.nio package

    String host = ...; 
    InetSocketAddress socketAddress = new InetSocketAddress(host, 80); 
    channel = SocketChannel.open(); 
    channel.configureBlocking(false); 
    channel.connect(socketAddress);
    

提交回复
热议问题