如何查看 Python 中是否有可用且活动的网络连接?

编程入门 行业动态 更新时间:2024-10-22 02:42:52
本文介绍了如何查看 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('216.58.192.142', timeout=1) return True except urllib2.URLError as err: return False

目前,216.58.192.142 是 google 的 IP 地址之一.将 216.58.192.142 更改为可以预期快速响应的任何站点.

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

这个固定 IP 不会永远映射到 google.所以这段代码是不健壮——它需要不断的维护才能保持工作.

This fixed IP will not map to google 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(在 unix 上)的当前 IP 地址

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

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

更多推荐

如何查看 Python 中是否有可用且活动的网络连接?

本文发布于:2023-11-11 18:24:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1579218.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:网络   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!