测试python中是否存在internet连接
我有以下代码来检查是否存在internet连接测试python中是否存在internet连接,python,python-2.7,networking,Python,Python 2.7,Networking,我有以下代码来检查是否存在internet连接 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 这将测试internet连接,但效果如何 我知道互联网的质量因人而异
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
这将测试internet连接,但效果如何
我知道互联网的质量因人而异,所以我正在寻找对广谱最有效的东西,上面的代码似乎有漏洞,人们可能会在其中发现bug。例如,如果某人的连接速度非常慢,并且响应时间超过20秒。是否将超时时间增加到30秒?做多次尝试?尝试几台主机?Http对于检查网络可用性来说似乎太高了
尽管如此,您可以创建一个线程来定期检查连接并存储连接状态,接下来internet_on方法可以只检查存储的状态。这应该比每次测试连接都要快。我的方法如下:
import socket
REMOTE_SERVER = "one.one.one.one"
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
如果没有连接(OSX、Python 2.7),这将在不到一秒钟内返回
注意:此测试可能返回误报——例如,DNS查找可能返回本地网络中的服务器。要真正确保您已连接到internet,并与有效主机通信,请确保使用更复杂的方法(例如SSL) 这会有用的
import urllib
try :
stri = "https://www.google.co.in"
data = urllib.urlopen(stri)
print "Connected"
except e:
print "not connected" ,e
这就是我使用的:
import subprocess
subprocess.call('ping -t 8.8.8.8')
我想在一个无限循环中测试我的互联网连接,以监控我的网络何时上下波动。我注意到如下情况:当我的网络关闭时,我像那样启动监控脚本,然后网络恢复,脚本没有注意到。网络是活跃的,但脚本没有看到。当我的网络打开,我像那样启动脚本时,它注意到了变化。因此,我提出了以下两种情况下都适用的解决方案:
import shlex
from subprocess import call, PIPE, STDOUT
def get_return_code_of_simple_cmd(cmd, stderr=STDOUT):
"""Execute a simple external command and return its exit status."""
args = shlex.split(cmd)
return call(args, stdout=PIPE, stderr=stderr)
def is_network_alive():
cmd = "ping -c 1 www.google.com"
return get_return_code_of_simple_cmd(cmd) == 0
在这里,我们依赖于一个独立于脚本的外部程序(
ping
)。我希望,我可以帮助您解决这个问题
import urllib
try :
url = "https://www.google.com"
urllib.urlopen(url)
status = "Connected"
except :
status = "Not connect"
print status
从Python2.6和更新版本(包括Python3)开始,一个与IPv6兼容的更简单的解决方案是
import socket
def is_connected():
try:
# connect to the host -- tells us if the host is actually
# reachable
socket.create_connection(("1.1.1.1", 53))
return True
except OSError:
pass
return False
它解析名称,并尝试连接到每个返回地址,然后确定其处于脱机状态。这还包括IPv6地址。虽然答案已勾选,但对我没有帮助,我遇到了如下错误 urllib2未定义 因此,我尝试使用pip安装urllib2库,但无能为力,于是我四处寻找,幸运的是我找到了解决方案 请检查下面的代码,因为有人谁将面临的问题,我以前有,将得到解决方案
from urllib.request import urlopen
def is_internet_available():
try:
urlopen('http://216.58.192.142', timeout=1)
return True
except:
return False
print(is_internet_available())
我不需要每次检查都发帖子…所以我用它来通知设备从在线到离线,反之亦然
导入套接字
导入时间
mem1=0
尽管如此:
尝试:
host=socket.gethostbyname(
“www.google.com”
)#更改为个人选择的网站
s=套接字。创建_连接((主机,80),2)
s、 关闭()
mem2=1
如果mem2==mem1:
通过#在每次检查时添加要执行的命令
其他:
mem1=mem2
打印(“互联网正在运行”)#将在状态更改时执行
例外情况除外,如e:
mem2=0
如果mem2==mem1:
通过
其他:
mem1=mem2
打印(“互联网关闭”)
时间。睡眠(10)#检查时间间隔
我已经用了一段时间了,
很好
import requests
while True:
try:
requests.get('https://www.google.com/').status_code
break
except:
time.sleep(5)
pass
这是我的代码,工作正常
import requests
try:
requests.get('https://www.google.com/').status_code
print("Connected")
except:
print("Not Connected")
exit()
检查互联网可用性的有效方法(修改@andrebrait的答案)
导入套接字
def已断开连接():
尝试:
#连接到主机--告诉我们主机是否确实是
#可达
sock=socket.create_连接((“www.google.com”,80))
如果sock不是无:
打印('闭合插座')
短袜
返回真值
除操作错误外:
通过
返回错误
作为补充;很多情况都可能发生
socket.gethostbyname
)
socket.gethostbyname
)也将表明与internet的连接丢失
socket.create\u connection
socket.create_connection
将失败,因为TCP套接字需要指向代理,而不是最终主机。您可以使用urllib.getproxies
(python 2)或urllib.request.getproxies
(python 3)获取当前代理配置。因此,在使用urllib.parse.urlparse
识别代理信息之后,您可以使用urllib
of-更简单的请求
建立一个HTTP访问某个已知url
urllib
或请求所使用的OS环境变量中配置代理,而是逐个配置他的工具,则最后一种方法可能会失败(表示没有连接,而实际上有连接)(例如,conda
使用.condarc
代理服务器
部分)。在这种情况下,除了检查工具的代理配置文件外,没有神奇的方法检测故障是否来自错误的代理配置或internet连接丢失
import socket
IPaddress=socket.gethostbyname(socket.gethostname())
if IPaddress=="127.0.0.1":
print("No internet, your localhost is "+ IPaddress)
else:
print("Connected, with the IP address: "+ IPaddress )
from datetime import datetime
import time, os, requests
from termcolor import colored
os.system('color')
url = 'https://www.google.com/'
timeout = 2
sleep_time = 10
op = None
while True:
now = datetime.now()
try:
op = requests.get(url, timeout=timeout).status_code
if op == 200:
print(now, colored("Connected", "green"))
sleep_time = 10
else:
print(now, colored("Status Code is not 200", "red"))
print("status Code", op)
except:
print(now, colored("Not Connected", "red"))
print("status Code", op)
sleep_time = 5
time.sleep(sleep_time)
import urllib.request
def connect():
host='http://google.com'
try:
urllib.request.urlopen(host) #Python 3.x
return True
except:
return False
import ntplib
import datetime, time
try:
client = ntplib.NTPClient()
response = client.request('pool.ntp.org')
Internet_date_and_time = datetime.datetime.fromtimestamp(response.tx_time)
print('\n')
print('Internet date and time as reported by server: ',Internet_date_and_time)
except OSError:
print('\n')
print('Internet date and time could not be reported by server.')
print('There is not internet connection.')
import urllib
from urllib.request import urlopen
def is_internet():
"""
Query internet using python
:return:
"""
try:
urlopen('https://www.google.com', timeout=1)
return True
except urllib.error.URLError as Error:
print(Error)
return False
if is_internet():
print("Internet is active")
else:
print("Internet disconnected")
print((lambda a: 'Internet connected and working' if 0 == a.system('ping google.com -w 4 > clear') else 'Internet not connected.')(__import__('os')))