java 检查网络,Java快速检查网络连接

该问题探讨了在Java5环境下如何实现对网络连接的即时检测,避免使用阻塞方法等待超时。作者提到了两种方法:HTTP请求和Socket连接,但两者都会在超时后才返回结果。解决方案是利用Java5的`InetAddress`类的`isReachable()`方法,结合指定超时时间,或者使用非阻塞的Java NIO进行网络检查。
摘要由CSDN通过智能技术生成

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 features of NetworkInterface.

Currently I have two different methods of checking for a network connection:

(try..catches removed)

Method One:

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;

Method 2:

Socket socket = new Socket("www.google.com", 80);

netAccess = socket.isConnected();

socket.close();

return netAccess;

However, both of these methods block until a Timeout is reached before returning false. I need a method that will return immediately, but is compatible with Java 5.

Thanks!

EDIT:

I forgot to mention that my program is reliant on IP addresses, not DNS names. So checking for an error when resolving a host is out...

2nd EDIT:

Figured out a final solution using NetworkInterface:

Enumeration eni = NetworkInterface.getNetworkInterfaces();

while(eni.hasMoreElements()) {

Enumeration 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;

}

}

}

解决方案

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);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值