简体   繁体   English

如何检查计算机是否已连接到互联网?

[英]How to check if the computer is connected to the internet?

I have seen that this question had been asked before in SO. 我已经看到在SO中曾经问过这个问题。 Some of the threads are: 一些线程是:

All these threads are pretty old. 所有这些线程都相当老。 The approaches that are defined there are: 定义的方法有:

  • Opening an HttpURLConnection by openConnection() . 通过openConnection()打开HttpURLConnection
  • Checking InetAddress.isReachable . 检查InetAddress.isReachable
  • Executing ping command through Process and processing the output. 通过Process执行ping命令并处理输出。

I have seen if I use the second approach to check the connectivity with www.google.com then it is returning false, which should not be the result. 我已经知道,如果我使用第二种方法来检查与www.google.com的连接,那么它将返回false,这不应是结果。 But the first way works. 但是第一种方法可行。 I cannot use the last way since the respondent himself said it. 自从受访者本人说过后,我就无法使用最后一种方式。

I have also seen the following way: 我也看到了以下方式:

private boolean isConnected(Socket socket, String address) {
    if(socket == null) {
        throw new NullPointerException("Socket cannot be null");            
    }

    try {
        InetSocketAddress inetSocketAddress = new InetSocketAddress(address, 80);
        socket.connect(inetSocketAddress);
        return true;
    } catch (Throwable cause) {
        LOGGER.error(cause.getMessage(), cause);
        return false;
    }
}

By this way I am getting right output. 通过这种方式,我得到正确的输出。 The aforementioned threads mentioned that there is no proper way to validate if the computer is connected to the internet or not. 前面提到的线程提到没有正确的方法来验证计算机是否已连接到Internet。 But since these threads are old so I am hoping there might be some new way out there by which I can achieve what I want. 但是由于这些线程很旧,所以我希望可能有一些新的方法可以实现我想要的目标。 Also I have to consider that there are various ways to access internet like LAN, Broadband, Dial Up, DSL etc and some server might block ping access or can block some IP. 我还必须考虑到有多种访问Internet的方式,例如LAN,宽带,拨号,DSL等,并且某些服务器可能会阻止ping访问或可以阻止某些IP。

Any pointer would be very helpful. 任何指针都将非常有帮助。

You could use the NetworkInterface class, it has a isUp() method which returns boolean indicating whether the particular interface is up and running (which could indicate if it's used for internet connection). 您可以使用NetworkInterface类,它具有isUp()方法,该方法返回boolean,以指示特定接口是否已启动并正在运行(这可以指示该接口是否用于Internet连接)。

API: http://docs.oracle.com/javase/7/docs/api/java/net/NetworkInterface.html API: http : //docs.oracle.com/javase/7/docs/api/java/net/NetworkInterface.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM