如何检查Java中是否存在互联网连接?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1402005/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if internet connection is present in Java?
提问by Chris
How do you check if you can connect to the internet via java? One way would be:
你如何检查你是否可以通过java连接到互联网?一种方法是:
final URL url = new URL("http://www.google.com");
final URLConnection conn = url.openConnection();
... if we got here, we should have net ...
But is there something more appropriate to perform that task, especiallyif you need to do consecutive checksvery often and a loss of internet connection is highly probable?
但是是否有更适合执行该任务的方法,特别是如果您需要经常进行连续检查并且很可能会丢失互联网连接?
采纳答案by Jon Skeet
You should connect to the place that your actual application needs. Otherwise you're testing whether you have a connection to somewhere irrelevant (Google in this case).
您应该连接到您的实际应用程序需要的地方。否则,您正在测试您是否与某个不相关的地方(在这种情况下为 Google)有连接。
In particular, if you're trying to talk to a web service, and if you're in control of the web service, it would be a good idea to have some sort of cheap "get the status" web method. That way you have a much better idea of whether your "real" call is likely to work.
特别是,如果您正在尝试与 Web 服务对话,并且您可以控制该 Web 服务,那么使用某种廉价的“获取状态”Web 方法将是一个好主意。这样您就可以更好地了解您的“真实”通话是否可行。
In other cases, just opening a connection to a port that should be open may be enough - or sending a ping. InetAddress.isReachable
may well be an appropriate API for your needs here.
在其他情况下,只需打开与应该打开的端口的连接就足够了 - 或者发送 ping。InetAddress.isReachable
在这里很可能是满足您需求的合适 API。
回答by Justin Niessner
1) Figure out where your application needs to be connecting to.
1) 找出您的应用程序需要连接到的位置。
2) Set up a worker process to check InetAddress.isReachableto monitor the connection to that address.
2) 设置一个工作进程来检查InetAddress.isReachable以监控到该地址的连接。
回答by Stephen C
People have suggested using INetAddress.isReachable. The problem is that some sites configure their firewalls to block ICMP Ping messages. So a "ping" might fail even though the web service is accessible.
人们建议使用 INetAddress.isReachable。问题在于某些站点将其防火墙配置为阻止 ICMP Ping 消息。因此,即使可以访问 Web 服务,“ping”也可能会失败。
And of course, the reverse is true as well. A host may respond to a ping even though the webserver is down.
当然,反过来也是如此。即使网络服务器关闭,主机也可能响应 ping。
And of course, a machine may be unable to connect directly to certain (or all) web servers due to local firewall restrictions.
当然,由于本地防火墙的限制,机器可能无法直接连接到某些(或所有)Web 服务器。
The fundamental problem is that "can connect to the internet" is an ill-defined question, and this kind of thing is difficult to test without:
最根本的问题是“能不能上网”是一个不明确的问题,这种东西很难测试,没有:
- information on the user's machine and "local" networking environment, and
- information on what the app needs to access.
- 有关用户机器和“本地”网络环境的信息,以及
- 关于应用程序需要访问什么的信息。
So generally, the simplest solution is for an app to just try to access whatever it needs to access, and fall back on human intelligence to do the diagnosis.
所以一般来说,最简单的解决方案是让应用程序尝试访问它需要访问的任何内容,然后依靠人类智能来进行诊断。
回答by Kutzi
If you're on java 6 can use NetworkInterfaceto check for available network interfaces. I.e. something like this:
如果您使用的是 java 6,则可以使用NetworkInterface检查可用的网络接口。即这样的事情:
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface interf = interfaces.nextElement();
if (interf.isUp() && !interf.isLoopback())
return true;
}
Haven't tried it myself, yet.
自己还没有试过。
回答by Rushil
URL url=new URL("http://[any domain]");
URLConnection con=url.openConnection();
/*now errors WILL arise here, i hav tried myself and it always shows "connected" so we'll open an InputStream on the connection, this way we know for sure that we're connected to d internet */
/* Get input stream */
con.getInputStream();
Put the above statements in try catch blocks and if an exception in caught means that there's no internet connection established. :-)
将上述语句放在 try catch 块中,如果 catch 中出现异常意味着没有建立互联网连接。:-)
回答by Marcus Adams
I usually break it down into three steps.
我通常把它分成三个步骤。
- I first see if I can resolve the domain name to an IP address.
- I then try to connect via TCP (port 80 and/or 443) and close gracefully.
- Finally, I'll issue an HTTP request and check for a 200 response back.
- 我先看看能不能把域名解析成IP地址。
- 然后我尝试通过 TCP(端口 80 和/或 443)连接并正常关闭。
- 最后,我将发出一个 HTTP 请求并检查是否有 200 响应。
If it fails at any point, I provide the appropriate error message to the user.
如果它在任何时候失败,我会向用户提供适当的错误消息。
回答by Mordechai
This code:
这段代码:
"127.0.0.1".equals(InetAddress.getLocalHost().getHostAddress().toString());
Returns - to me - true
if offline, and false
, otherwise. (well, I don't know if this true to all computers).
返回 - 给我 -true
如果离线false
,否则返回。(好吧,我不知道这是否适用于所有计算机)。
This works much faster than the other approaches, up here.
这比这里的其他方法要快得多。
EDIT: I found this only working, if the "flip switch" (on a laptop), or some other system-defined option, for the internet connection, is off. That's, the system itself knows not to look for any IP addresses.
编辑:我发现这只有在“翻转开关”(在笔记本电脑上)或其他一些系统定义的选项(用于互联网连接)关闭时才有效。也就是说,系统本身知道不寻找任何 IP 地址。
回答by blue-sky
This code is contained within a jUnit test class I use to test if a connection is available. I always receive a connection, but if you check the content length it should be -1 if not known :
此代码包含在我用来测试连接是否可用的 jUnit 测试类中。我总是收到一个连接,但如果你检查内容长度,如果不知道,它应该是 -1:
try {
URL url = new URL("http://www.google.com");
URLConnection connection = url.openConnection();
if(connection.getContentLength() == -1){
fail("Failed to verify connection");
}
}
catch (IOException e) {
fail("Failed to open a connection");
e.printStackTrace();
}
回答by harald
The code using NetworkInterface to wait for the network worked for me until I switched from fixed network address to DHCP. A slight enhancement makes it work also with DHCP:
使用 NetworkInterface 等待网络的代码对我有用,直到我从固定网络地址切换到 DHCP。一个轻微的增强使它也适用于 DHCP:
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface interf = interfaces.nextElement();
if (interf.isUp() && !interf.isLoopback()) {
List<InterfaceAddress> adrs = interf.getInterfaceAddresses();
for (Iterator<InterfaceAddress> iter = adrs.iterator(); iter.hasNext();) {
InterfaceAddress adr = iter.next();
InetAddress inadr = adr.getAddress();
if (inadr instanceof Inet4Address) return true;
}
}
}
This works for Java 7 in openSuse 13.1 for IPv4 network. The problem with the original code is that although the interface was up after resuming from suspend, an IPv4 network address was not yet assigned. After waiting for this assignment, the program can connect to servers. But I have no idea what to do in case of IPv6.
这适用于 IPv4 网络的 openSuse 13.1 中的 Java 7。原代码的问题是,虽然接口在从挂起状态恢复后是 up 的,但还没有分配 IPv4 网络地址。等待此分配后,程序可以连接到服务器。但是我不知道在 IPv6 的情况下该怎么做。
回答by Marcus Junius Brutus
The code you basically provided, plus a call to connect
should be sufficient. So yeah, it could be that just Google's not available but some other site you need to contact is on but how likely is that? Also, this code should only execute when you actually fail to access your external resource (in a catch
block to try and figure out what the cause of the failure was) so I'd say that if both your external resource of interest andGoogle are not available chances are you have a net connectivity problem.
您基本上提供的代码加上调用就connect
足够了。所以是的,可能只是 Google 不可用,但您需要联系的其他一些网站正在运行,但可能性有多大?此外,此代码仅应在您实际无法访问外部资源时执行(在一个catch
块中尝试找出失败的原因)所以我想说的是,如果您感兴趣的外部资源和Google 都不是可用机会是您有网络连接问题。
private static boolean netIsAvailable() {
try {
final URL url = new URL("http://www.google.com");
final URLConnection conn = url.openConnection();
conn.connect();
conn.getInputStream().close();
return true;
} catch (MalformedURLException e) {
throw new RuntimeException(e);
} catch (IOException e) {
return false;
}
}