Socket Exception couldn't reconnect to the network in python - python

when the network goes offline, the sockets throws error instead of reconnecting. It is reconnecting but not trying to achieve the connection. throws error in second or third attempt. Do I need to increase the wait time or is there anything which can be added to make sure the reconnect takes place
import socket,time
client=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
client.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
ip = '192.168.xx.x'
port = 4196
address = (ip,port)
client.connect(address)
print("connecting")
while 1:
try:
client.send(b'\x01\x04xxxxxxx')
print("sent")
data = client.recv(1024)
print(data)
time.sleep(5)
except socket.error:
while 1:
print("error")
client.close()
time.sleep(30)
print("reconnecting")
client=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
while 1:
client.connect(address)
print("connected back")
break
break
OutPut:
connecting
sent
01 04 xxxxxxxxx
error
reconnecting
Error:
Traceback (most recent call last):
File "C:\Users\User\eclipse-workspace\Data\pwr\TCP.py", line 15, in <module>
client.send(b'\x01\x04\xxxxxxxxxxx')
ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\User\eclipse-workspace\Data\pwr\TCP.py", line 28, in <module>
client.connect(address)
ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine

Related

Receive data from a client/server doesn't work

I developed a small Python program which should receive and output data from another client or server. However, I get an error message which is unknown to me. Can anyone help me? Thanks a lot
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('192.168.1.34', 80))
from_server = client.recv(4096)
client.close()
print from_server
Error:
Traceback (most recent call last):
File "CallManager2.py", line 4, in <module>
client.connect(('192.168.1.34', 80))
File "/usr/lib/python2.7/socket.py", line 228, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 111] Connection refused
The error comes from inability for your program to reach the server or other client.
Check that there is something listening to incoming connexions on the address you want to connect to.
Then you can check that the address you want to connect to is on the same network as your program.

paramiko exception for connection refused

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"

Why am I getting a "Connection refused" in python? Can't resolve using existing solutions

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.

Python Socket Error Handling

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.

How to close socket after python fail?

First, I encountered sockets in Python and faced this problem: when some error in my python code occurs, for example some syntax error before conn.close() on the second script start port is in use. The script already finished, but the socket is still open, kind of like busy socket.
Here is an error just for example:
web#web-X501A1 /var/www $ cd /home/web/www/public/py
web#web-X501A1 ~/www/public/py $ python sockets.py
connected: ('127.0.0.1', 47168)
Traceback (most recent call last):
File "sockets.py", line 164, in <module>
data = re.find('(<onvif>.*<\/onvif>)')
AttributeError: 'module' object has no attribute 'find'
web#web-X501A1 ~/www/public/py $ python sockets.py
Traceback (most recent call last):
File "sockets.py", line 154, in <module>
sock.bind(('', 9090))
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 98] Address already in use
web#web-X501A1 ~/www/public/py $ python sockets.py
Traceback (most recent call last):
File "sockets.py", line 154, in <module>
sock.bind(('', 9090))
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 98] Address already in use
Code:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('', 9090))
sock.listen(1)
conn, addr = sock.accept()
try:
print 'connected:', addr
buffer = ''
while True:
buffer += conn.recv(1024)
data = re.find('(<code>.*<\/code>)', buffer)
print data
exit();
if not data:
continue
conn.send(data.upper())
except Exception:
pass
finally:
conn.close()
Enclose the usage of the socket in a try/finally clause. Close the socket in the finally part. Perhaps handle the exception in an except part. Something similar to this:
try:
result = x / y
except ZeroDivisionError:
print "division by zero!"
else:
print "result is", result
finally:
print "executing finally clause"
The problem here is the dirty socket closing which occurs when the script crashes without the proper TCP connection shutdown sequence. Thankfully there's a simple solution which tells the kernel to ignore the fact the socket is already in use (the port it's bound to):
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
That's all, add that before the bind call and you're set. Debugging your other errors will be much simpler and less time consuming once that's done ;) See more in the docs https://docs.python.org/2/library/socket.html#socket.socket.setsockopt
If you use netstat -nutap you should notice that you connection seems like it's still up, on a state named TIME_WAIT.
That's part of TCP protocol, and according to wikipedia:
represents waiting for enough time to pass to be sure the remote TCP
received the acknowledgment of its connection termination request.
[According to RFC 793 a connection can stay in TIME-WAIT for a maximum
of four minutes known as a MSL (maximum segment lifetime).]
So, when you try to reconnect immediately to the same port, python complains that this port is still busy and cant be bound yet, saying:
socket.error: [Errno 98] Address already in use
See this old question, where it is asked how to avoid this waiting time.

Categories