Jos*_*rot 27 python networking python-2.7
我有以下代码检查是否存在互联网连接.
import urllib2
def internet_on():
try:
response=urllib2.urlopen('http://74.125.228.100',timeout=20)
return True
except urllib2.URLError as err: pass
return False
Run Code Online (Sandbox Code Playgroud)
这将测试互联网连接,但效果如何?
我知道互联网的质量因人而异,所以我正在寻找对广谱来说最有效的东西,上面的代码似乎可能存在漏洞,人们可能会发现漏洞.例如,如果某人的连接速度非常慢,并且花了超过20秒的时间来响应.
mir*_*ixx 49
我的方法是这样的:
import socket
REMOTE_SERVER = "www.google.com"
def is_connected(hostname):
try:
# see if we can resolve the host name -- tells us if there is
# a DNS listening
host = socket.gethostbyname(hostname)
# connect to the host -- tells us if the host is actually
# reachable
s = socket.create_connection((host, 80), 2)
s.close()
return True
except:
pass
return False
%timeit is_connected(REMOTE_SERVER)
> 10 loops, best of 3: 42.2 ms per loop
Run Code Online (Sandbox Code Playgroud)
如果没有连接(OSX,Python 2.7),这将在不到一秒的时间内返回.
注意:此测试可能会返回误报 - 例如,DNS查找可能会返回本地网络中的服务器.要确定您已连接到互联网,并与有效的主机交谈,请务必使用更复杂的方法(例如SSL).
and*_*ait 14
从Python 2.6及更新版本(包括Python 3)开始,一个更简单的解决方案也将与IPv6兼容
import socket
def is_connected():
try:
# connect to the host -- tells us if the host is actually
# reachable
socket.create_connection(("www.google.com", 80))
return True
except OSError:
pass
return False
Run Code Online (Sandbox Code Playgroud)
它解析名称并尝试连接到每个返回地址,然后结束它是否脱机.这还包括IPv6地址.
检查互联网可用性的有效方法(修改后的@andrebrait 的答案)。
import socket
def isConnected():
try:
# connect to the host -- tells us if the host is actually
# reachable
sock = socket.create_connection(("www.google.com", 80))
if sock is not None:
print('Clossing socket')
sock.close
return True
except OSError:
pass
return False
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
56628 次 |
最近记录: |