检查网络连接 [英] Checking network connection

查看:107
本文介绍了检查网络连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想看看是否可以访问在线API,但是为此我需要访问Internet.

I want to see if I can access an online API, but for that I need to have Internet access.

如何查看使用Python的连接是否可用并处于活动状态?

How can I see if there's a connection available and active using Python?

推荐答案

也许您可以使用类似这样的东西:

Perhaps you could use something like this:

import urllib2

def internet_on():
    try:
        urllib2.urlopen('http://216.58.192.142', timeout=1)
        return True
    except urllib2.URLError as err: 
        return False

当前,216.58.192.142是google.com的IP地址之一. http://216.58.192.142更改为可以快速响应的任何站点.

Currently, 216.58.192.142 is one of the IP addresses for google.com. Change http://216.58.192.142 to whatever site can be expected to respond quickly.

此固定IP不会永远映射到google.com.所以这段代码是 不够健壮-它将需要不断维护以保持其正常运行.

This fixed IP will not map to google.com forever. So this code is not robust -- it will need constant maintenance to keep it working.

上面的代码使用固定IP地址而不是完全限定域名(FQDN)的原因是因为FQDN需要进行DNS查找.当机器没有有效的Internet连接时,DNS查找本身可能会阻止对urllib_request.urlopen的呼叫超过一秒钟.感谢@rzetterberg指出这一点.

The reason why the code above uses a fixed IP address instead of fully qualified domain name (FQDN) is because a FQDN would require a DNS lookup. When the machine does not have a working internet connection, the DNS lookup itself may block the call to urllib_request.urlopen for more than a second. Thanks to @rzetterberg for pointing this out.

如果上面的固定IP地址不起作用,您可以通过运行来查找google.com(在Unix上)的当前IP地址

If the fixed IP address above is not working, you can find a current IP address for google.com (on unix) by running

% dig google.com  +trace 
...
google.com.     300 IN  A   216.58.192.142

这篇关于检查网络连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆