I Have to check if my computer is connected to internet (so if i open the broswer i can or i cannot visit an url) , for do this task i tried with some codes:
The first is
import socket
def internet_on():
try:
print("checking internet connection..")
socket.setdefaulttimeout(5)
host = socket.gethostbyname("www.google.com")
s = socket.create_connection((host, 80), 2)
s.close()
print('internet on.')
return True
except Exception as e:
print(e)
print("internet off.")
return False
internet_on()
code that i took from this answer Checking internet connection with Python
After i tried with this:
from urllib.request import urlopen
def internet_on():
try:
urlopen("https://www.instagram.com/", timeout=5)
return True
except Exception as err:
print(str(err))
return False
internet_on()
code that i took from this answer Checking network connection
And this
import socket
REMOTE_SERVER = "www.google.com"
def internet_on(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)
return True
except Exception:
return False
internet_on(REMOTE_SERVER)
code that i took from this answer Test if an internet connection is present in python
If the connection is active the codes work fines
but when there is no connection all this codes raise the same errors:
Traceback (most recent call last):
File "C:\Users\mcara\PycharmProjects\1\venv\lib\site-packages\urllib3\connection.py", line 159, in _new_conn
(self._dns_host, self.port), self.timeout, **extra_kw)
File "C:\Users\mcara\PycharmProjects\1\venv\lib\site-packages\urllib3\util\connection.py", line 57, in create_connection
for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM):
File "C:\Program Files\Python37-32\lib\socket.py", line 748, in getaddrinfo
for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno 11001] getaddrinfo failed
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\mcara\PycharmProjects\1\venv\lib\site-packages\urllib3\connectionpool.py", line 600, in urlopen
chunked=chunked)
File "C:\Users\mcara\PycharmProjects\1\venv\lib\site-packages\urllib3\connectionpool.py", line 343, in _make_request
self._validate_conn(conn)
File "C:\Users\mcara\PycharmProjects\1\venv\lib\site-packages\urllib3\connectionpool.py", line 839, in _validate_conn
conn.connect()
File "C:\Users\mcara\PycharmProjects\1\venv\lib\site-packages\urllib3\connection.py", line 301, in connect
conn = self._new_conn()
File "C:\Users\mcara\PycharmProjects\1\venv\lib\site-packages\urllib3\connection.py", line 168, in _new_conn
self, "Failed to establish a new connection: %s" % e)
urllib3.exceptions.NewConnectionError: <urllib3.connection.VerifiedHTTPSConnection object at 0x03B39E90>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\mcara\PycharmProjects\1\venv\lib\site-packages\requests\adapters.py", line 449, in send
timeout=timeout
File "C:\Users\mcara\PycharmProjects\1\venv\lib\site-packages\urllib3\connectionpool.py", line 638, in urlopen
_stacktrace=sys.exc_info()[2])
File "C:\Users\mcara\PycharmProjects\1\venv\lib\site-packages\urllib3\util\retry.py", line 398, in increment
raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='www.instagram.com', port=443): Max retries exceeded with url: /_exploreurself (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x03B39E90>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed'))
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:/Users/mcara/OneDrive/Desktop/file InstaBot da editare/v0.4/bot.py", line 835, in <module>
bot.unfollow_process(RANDOM, sense=UP_DOWN, following_target=0, sleep_time=60)
File "C:/Users/mcara/OneDrive/Desktop/file InstaBot da editare/v0.4/bot.py", line 651, in unfollow_process
current_following = self.user_following_num(self._username)
File "C:/Users/mcara/OneDrive/Desktop/file InstaBot da editare/v0.4/bot.py", line 387, in user_following_num
r = requests.get(url).text
File "C:\Users\mcara\PycharmProjects\1\venv\lib\site-packages\requests\api.py", line 75, in get
return request('get', url, params=params, **kwargs)
File "C:\Users\mcara\PycharmProjects\1\venv\lib\site-packages\requests\api.py", line 60, in request
return session.request(method=method, url=url, **kwargs)
File "C:\Users\mcara\PycharmProjects\1\venv\lib\site-packages\requests\sessions.py", line 533, in request
resp = self.send(prep, **send_kwargs)
File "C:\Users\mcara\PycharmProjects\1\venv\lib\site-packages\requests\sessions.py", line 646, in send
r = adapter.send(request, **kwargs)
File "C:\Users\mcara\PycharmProjects\1\venv\lib\site-packages\requests\adapters.py", line 516, in send
raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='www.instagram.com', port=443): Max retries exceeded with url: /_exploreurself (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x03B39E90>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed'))
Try this one here IP address 216.58.192.142 is one of Google's IP address. Due to static IP address, this code is not robust and may not work always so, replace this IP address with some other website which you believe respond more faster.
The reason why the code uses a fixed IP address instead of a fully qualified domain name (FQDN) is because a FQDN would require a DNS lookup. When the machine does not have a working internet connection, the DNS lookup itself may block the call to urllib_request.urlopen for more than a second.
import urllib2
def internet_on():
try:
urllib2.urlopen('http://216.58.192.142', timeout=1)
return True
except urllib2.URLError as err:
return False
Try to run a ping to www.google.com with the library 'subprocess', an example of code below. This solution is an indirect one, but sometimes is better to delegate in system commands to do certain jobs like this one.
import subprocess
def my_dir(my_path):
output=''
try:
p = subprocess.Popen('ping '+my_path, stdout = subprocess.PIPE, stderr = subprocess.STDOUT,
#close_fds = True, #not valid for Windows platforms
shell = True
)
output, err = p.communicate()
#print(output)
finally:
if p is not None:
try: p.kill()
except: pass
return output
print(my_dir('www.google.com'))
Then, you can parse its output to know if you have reached Google's servers or not.
import paramiko
try:
ssh =paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname='10.10.1.0',username='test',password='test1234')
print 'Successfully connected'
except paramiko.AuthenticationException:
print "Authentication failed, please verify your credentials"
except paramiko.SSHException as sshException:
print "Unable to establish SSH connection: %s" % sshException
This is my code. It was working fine.
If i give wrong userid and password - Perfectly throwing expection.
But when hostname is not valid, it's throwing error as "Connection refused" and not sure what type of exception have to raise. Could some please help.
Error
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
File "/usr/lib/python2.6/site-packages/paramiko/client.py", line 290, in connect
sock.connect(addr)
File "<string>", line 1, in connect
socket.error: [Errno 111] Connection refused
socket.error is spelled socket_error like this:
from socket import error as socket_error
and then:
try:
# as you were
except socket_error as socket_err:
# do something
The error message is telling you about error numbers (socket_err.errno) so you can check that e.g. compare to errno.ECONNREFUSED.
Use this
import errno
try:
# Do something
except socket.error, v:
e_code = v[0]
if e_code == errno.ECONNREFUSED:
print "Connection Refused"
We have Hasseb USB Dali Master and try to used python library (github.com/sde1000/python-dali). But codes from section “Examples” don’t work.
We used Armbian Linux (Ubuntu based operating system)
The library https://github.com/onitake/daliserver was installed.
We try to start set_single.py separately.
$sudo python set_single.py
Traceback (most recent call last):
File "set_single.py", line 25, in <module> d.send(cmd)
File "build/bdist.linux-armv7l/egg/dali/driver/daliserver.py", line 43, in send
File "/usr/lib/python2.7/socket.py", line 575, in create_connection raise err
socket.error: [Errno 111] Connection refused
And try to start dalliserver in another terminal.
$ sudo python server.py
('Connection address_:', ('127.0.0.1', 43653))
Traceback (most recent call last):
File "server.py", line 14, in <module>
s.bind((TCP_IP, TCP_PORT))
File "/usr/lib/python2.7/socket.py", line 228, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 98] Address already in use
(This error occurred when set_single.py started)
$ sudo python set_single.py
Traceback (most recent call last):
File "set_single.py", line 25, in <module>
d.send(cmd)
File "build/bdist.linux-armv7l/egg/dali/driver/daliserver.py", line 66, in send
File "build/bdist.linux-armv7l/egg/dali/driver/daliserver.py", line 84, in unpack_response
struct.error: unpack requires a string argument of length 4
file set_single.py
from dali.address import Broadcast
from dali.address import Short
from dali.gear.general import DAPC
from dali.driver.daliserver import DaliServer
import sys
if __name__ == "__main__":
addr = Broadcast()
level = int(150)
d = DaliServer("localhost", 55825 )
cmd = DAPC(addr, level)
d.send(cmd)
file server.py
import socket
TCP_IP = '127.0.0.1'
TCP_PORT = 55825
BUFFER_SIZE = 20
while True:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)
conn, addr = s.accept()
try:
print("Connection address_:", addr)
while 1:
conn.setblocking(0)
conn.settimeout(20.0)
data = conn.recv(BUFFER_SIZE)
if not data:
break
stream = ":".join("{:02x}".format(ord(chr(c))) for c in data)
print("received data: [{1}] {0}".format(stream, len(data)))
conn.send(b"\x02\xff\x00\x00")
except:
pass
conn.close()
import ssl
import socket
port = 3001
while True:
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
ssl_socket = ssl.wrap_socket(s, cert_reqs=ssl.CERT_REQUIRED, ca_certs='scert.pem')
ssl_socket.connect(('127.0.0.1', 3001))
ssl_socket.write(str(input("Enter two numbers to add:")).encode())
z = ssl_socket.recv(1024)
print(z.decode())
ssl_socket.close()
The error I'm getting is:
Traceback (most recent call last):
ssl_socket.connect(('127.0.0.1', 3001))
self._real_connect(addr, False)
socket.connect(self, addr)
File "/usr/lib/python2.7/socket.py", line 228, in meth
return getattr(self._sock,name)(*args)
error: [Errno 111] Connection refused
I am confused as to what to do. Already tried the methods on the other thread on socket.
I'm trying to write socket error handling (exactly err 111 - Connection Refused) but nothing is happening. Terminal print that Errno 111 occured but it's not doing anything with it:
import errno
try:
#do something
except socket.error, v:
errorcode=v[0]
if errorcode==errno.ECONNREFUSED:
print "Connection Refused"
else:
print("Running Application")
Traceback (most recent call last): File "Test.py",
line 20, in
s.connect((IP, PORT)) File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args) socket.error: [Errno 111] Connection refused
Nothing else printed :/
What am I doing wrong ?
I think you need to use v.args[0] to get the error code.