Проверка наличия интернета python

Проверьте, существует ли интернет-соединение в python

У меня есть следующий код, который проверяет наличие интернет-соединения.

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 

Это проверит подключение к Интернету, но насколько оно эффективно?

Я знаю, что интернет отличается по качеству от человека к человеку, поэтому я ищу что-то, что наиболее эффективно для широкого спектра, и приведенный выше код кажется, что могут быть лазейки, где люди могут найти ошибки. Например, если у кого-то было очень медленное соединение и потребовалось больше 20 секунд, чтобы ответить.

Мой подход будет примерно таким:

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 

Это вернется менее чем за секунду, если нет соединения (OSX, Python 2.7).

Примечание. Этот тест может возвращать ложные срабатывания – например, поиск DNS может вернуть сервер в локальной сети. Чтобы быть уверенным, что вы подключены к Интернету и общаетесь с действительным хостом, используйте более сложные методы (например, SSL).

Как и в случае с 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 

Он разрешает имя и пытается подключиться к каждому возврату addres, прежде чем завершить его, в автономном режиме. Это также включает адреса IPv6.

import urllib try : stri = "https://www.google.co.in" data = urllib.urlopen(stri) print "Connected" except e: print "not connected" ,e 

Я хотел проверить подключение к Интернету в бесконечном цикле, чтобы отслеживать, когда моя сеть идет вверх и вниз. Я заметил следующее: когда моя сеть была отключена, и я начал мониторинг script, и сеть вернулась, script не заметил этого. Сеть была жива, но script этого не видел. Когда моя сеть была включена, и я начал script таким образом, он заметил изменения. Поэтому я придумал следующее решение, которое работало для меня в обоих случаях:

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 ), которая не зависит от нашего script.

Читайте также:  Java hashmap values to list

Http кажется слишком высоким для проверки доступности сети.

Тем не менее вы можете создать поток, который периодически проверяет подключение и сохраняет состояние подключения, а затем метод internet_on может просто проверять сохраненное состояние. Это будет быстрее, чем тестирование соединения каждый раз.

Надеюсь, я смогу помочь с вами.

import urllib try : url = "https://www.google.com" urllib.urlopen(url) status = "Connected" except : status = "Not connect" print status 

Хотя ответ был помечен, это не помогло мне, но я получил ошибку вроде

поэтому я попытался установить библиотеку urllib2 с помощью pip, но был беспомощен, затем я покопался и, к счастью, нашел решение, пожалуйста, проверьте следующий код и поделитесь им, потому что тот, кто столкнется с проблемой, с которой я столкнулся ранее, получит решение

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()) 
import subprocess subprocess.call('ping -t 8.8.8.8') 

Увеличьте время ожидания до 30 секунд? Сделайте несколько попыток? Попробуйте несколько хостов?

Источник

Python: Check internet connection

Python programing has many libraries and modules to check the internet connection status.

In this tutorial, we’ll use two methods to check the internet connection the requests library and the urllib module. Also, we’ll learn how to wait for the internet connection.

If you are ready, let’s get started.

Check internet connection using requests

First of all, we need to install requests.

If you don’t know about requests, check out w3chool-requests.

First, let’s write our code then explain how it works.

Initially, we import requests. Next, we try to send a request to google.com usingrequests.head() method.

If the request returns ConnectionError that means the internet connection is down, and if not, that means our internet is active.

timeout: wait (seconds) for the client to make a connection or send a response.

Let»s write our code as a function:

The is_cnx_active function return True or False.

Check internet connection using urllib.request.urlopen

With the urlopen function, we can also check the internet connection.

I think everything is clear, and no need to repeat the explanation.

How to wait for the internet connection

To wait for the internet connection, we’ll use while True statement with the is_cnx_active() function.

while True: loop forever.

The loop will break if is_cnx_active() returns True.

Источник

How to check the internet connection in Python?

Nowadays, the Internet is an essential part of our day-to-day lives. If the server is down even for a minute, then we check the Internet connectivity in various ways. Can Python help us check the connectivity? Yes, we can use Python language for checking the internet connection. In this tutorial, we will find out whether the computer is connected to the internet or not.

Checking Internet Connection in Python

Below we have described two methods of checking the internet connection in Python.

Читайте также:  Jquery this find html

By using an urllib package

To fetch URLs, we use urllib.request module in Python. This can fetch URLs using a variety of different protocols.

One of the functions present in the package are urllib.request.urlopen().
Syntax of urllib.request.urlopen() is

urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)

Here, we will specify only the URL. And the rest of the parameters to their default values.

Let’s see how to use it for checking the internet-

import urllib.request def connect(host='http://google.com'): try: urllib.request.urlopen(host) #Python 3.x return True except: return False # test print( "connected" if connect() else "no internet!" )

Initially, we import the urllib package. Then we used a function ‘connected()‘, whose parameter is the URL. It is unnecessary to use the URL as ’http://google.com’, it can be any URL. Inside the try block, we implemented the above method to check internet connectivity. As you can observe, instead of passing the URL, we have kept host over there which has the value of URL.
If the Internet connection is present, then it returns True else the control goes to except block and it returns False.
With the help of the print statement, if the returned value is true then ‘Connected’ else ‘no internet!’ is printed.

Let’s see the above program by not giving any parameter to the function-

import urllib.request def connect(): try: urllib.request.urlopen('http://google.com') #Python 3.x return True except: return False print( 'connected' if connect() else 'no internet!' )

Note: In Python 2.x, we replace urllib.request.urlopen() by urllib.urlopen() .

By using an IP address/By using socket package:

Here, we will use an indirect way when compared to the previous method.
127.0.0.1 is a special-purpose IPv4 address also known as localhost. All computers use this address as their own, however, it will not allow them to communicate with different devices as a real IP address does. The computer you’re on only uses the loopback address.

We import socket to check the connectivity. Socket programming is a method of connecting 2 nodes on a network to speak with one another.
You can find the IP using socket.gethostbyname() method. Below is the program to check the internet connection:

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 )
No internet, your localhost is 127.0.0.1

Initially, we import the socket package. Then fetch the IP address using socket.gethostbyname() method. When the Internet connection is absent, then it fetches the IP address as 127.0.0.1. Now, If-Else conditional statement is used to check whether or not the system is connected to the internet.

The above specified are the two ways to check the internet connection.

Источник

Проверка на наличие интернета

В общем нужно проверять в питоне, есть ли интернет. Есть ли спец. средства для этого или юзать os.system(‘ping ip’)? Если только второе, подскажите пожалуйста как получать вывод от него, что бы потом пропарсить?

Читайте также:  Progressbar python qt designer

Проверка на наличие файла
Как проверить, есть ли такой файл? Например, если есть файл, то в него дозаписать "123" Знаю.

Проверка на наличие файла и доступа к файлу
Здравствуйте, мне нужно протестировать свои методы с помощью библиотеки Pytest. Я написал такие.

Python + Selenium + webdriver проверка на наличие элем
Ребята всем доброго времени суток. Вопрос вот в чём , при собирании данных (а именно цены и кол-во.

Проверка на наличие чисел
Здравствуйте, только начал учить Python, вот прям ещё зачаточное состояние, пытаюсь разобраться с.

Лучший ответ

Сообщение было отмечено Lagovas как решение

Решение

1 2 3 4 5 6 7 8 9 10 11 12 13
>>> import socket >>> def f(): . try: . socket.gethostbyaddr('www.yandex.ru') . except socket.gaierror: . return False . return True . >>> f() True >>> f() False >>>

PyQt5 проверка на наличие элемента
from PyQt5 import QtCore, QtWidgets class Ui_MainWindow(): def setupUi(self, MainWindow).

Проверка на наличие файла в категории
Здравствуйте. Что я делаю не так? Поправьте пожалуйста код, с объяснением. import os .

Проверка на наличие слова в словаре
Здравствуйте! Нужна помощь, срочно. Есть два масива a = b = Нужно написать проверку на.

Проверка списка на наличие элемента
Дано 2 списка x и y, проверить содержит ли он число 2, вывести список, если содержит. Если не.

Проверка массива на наличие определенных данных
У меня есть строка, например "Привет, как твои дела?" Я её разбираю на массив и привожу всё к.

Проверка текста на наличие определенных символов
Выползает ошибка , когда проверяю текст на определенные символы, которые даны import string alf.

Проверка слова на наличие в файле txt
Я новичок и моя задача была найти слово в файле txt с набором русских слов. Вот, что у меня.

Источник

yasinkuyu / check_internet.py

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

#@yasinkuyu 08/09/2017
def check_internet ():
url = ‘http://www.google.com/’
timeout = 5
try :
_ = requests . get ( url , timeout = timeout )
return True
except requests . ConnectionError :
print ( «İnternet bağlantısı yok.» )
return False

Hi!
I tried your code and work very good, but it is important to specify that ‘requests’ package should be installed. For install it using python3:

pip3 install requests

The code above works but the «request» package needs to be installed.

If you are using «Python 3x», you should type «pip3 install requests» on the cmd screen,
If you are using «Python 2x (Default)», you should type «pip install requests» on the cmd screen.

In the latest stage: Do not forget to type «import requests» in the Python IDLE section.

Yukarıdaki kod işe yarıyor fakat «request» paketinin yüklü olması gerekiyor.

Eğer «Python 3x» kullanıyorsanız, cmd ekranına «pip3 install requests» yazmalı,
Eğer «Python 2x» kullanıyorsanız, cmd ekranına «pip install requests» yazmalısınız.

En son ki aşamada ise: Python IDLE kısmında «import requests» satırını yazmayı unutmayın.

Источник

Оцените статью