如何查看 Python 中是否有可用且活动的网络连接? [英] How can I see if there's an available and active network connection in Python?

查看:32
本文介绍了如何查看 Python 中是否有可用且活动的网络连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想看看我是否可以访问在线 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?

推荐答案

也许你可以这样使用:

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 查找.当机器没有可用的互联网连接时,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

这篇关于如何查看 Python 中是否有可用且活动的网络连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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