I'd like my Python script to check if it's online of not. Found pretty many answers here on Stack Overflow, but all failed for some weird reasons.
The scenario: a Raspberry Pi 3b+ connected to my router through Wifi. That said router is connected to internet through its cable
I wish to determine if the Raspberry has internet connection or not in order to change it's data source if needed. After searching here for the day, I found that the majority of the solutions use, for the better one, sockets, and for the worst ones (still tried to see if it changes anything, but no) urllib.urlopen
.
Here's what I try:
def checkOnlineState(self, addr='http://www.google.com'):
try:
urllib2.urlopen(addr, timeout=2)
if not self._onlineMode:
print('Internet connection is back!')
self._onlineMode = True
return
except:
pass
if self._onlineMode:
print('I lost internet connection')
self._onlineMode = False
I also tried with sockets, so instead of urllib2.urlopen I used
socket.create_connection((addr, 80), timeout=2)
or
socket.create_connection(('8.8.8.8', 0), timeout=2)
Whatever I do, except for entering a malformed ip or url, says I'm online. How do I know it? Well, the checkOnlineState runs in a loop, and if I take the internet cable off, the Raspberry still states it's online!
So, after the answer from @Sraw, this is what I finally did:
import requests
req = requests.get('http://clients3.google.com/generate_204')
if req.status_code != 204:
raise Exception
Yes, no exception, this is a heartbeat, I want to periodically check if I have access to internet, so whatever the error is, I want it signaled as offline
This won't fail because we check the request status. I found this way of doing here on Stackoverflow, on different questions.