Well... Am I Online Yet?

in #python7 years ago

net.jpg

How To Check For Internet Connection With Python



Just a quickie! I find this rather handy so I thought I'd share it. If we can get through to goGgle the response should be 200.

from requests import get
from requests.exceptions import ConnectionError


def is_online(timeout):
    try:
        r = get("https://google.com", timeout=timeout).status_code
    except ConnectionError:
        r = None
    if r == 200:
        return True
    else:
        return False



Then we can simply use it like so...

if is_online(10):
    print('ONLINE')
else:
    print('OFFLINE')



Or, as an alternative, we can throw it all into one function, make it sleep and basically plonk it anywhere you like.

from time import sleep
from requests import get
from requests.exceptions import ConnectionError


def wait_until_online(timeout, slumber):
    offline = 1
    while offline:
        try:
            r = get("https://google.com", timeout=timeout).status_code
        except ConnectionError:
            r = None
        if r == 200:
            print('ONLINE')
            offline = 0
        else:
            print('OFFLINE')
            sleep(slumber)



And use it like this...

wait_until_online(10, 900)



Thanks for reading. x

Resources

Coin Marketplace

STEEM 0.05
TRX 0.33
JST 0.080
BTC 63398.51
ETH 1702.04
USDT 1.00
SBD 0.41