Not able to connect a different IP after being able to connect the first time
class Client():
def __init__(self):
self.host = None
self.ip = None
self.error_count = 0
self._load_ip()
self._load_certs()
self._build_context()
self.connect()
def _load_ip(self):
self.ip = '19x.x.4'
self.port = xxxx
def _load_certs(self):
self.cert = '/path/'
def _build_context(self):
self.s = socket.socket(socket.AF_NET, socket.SOCK_STREAM)
self.context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
self.context.load_verify_locations(self.cert)
def connect(self):
try:
self.conn = self.context.wrap_socket(self.s, server_side=False)
self.conn.connect((self.ip, self.port))
return self.conn
except Exception as ex:
if self.error_count <=1:
self.error_count =1
self.ip = '19x.x.5'
self.conn.close() # close the previous connection
self._build_context() # call this function again for new socket
self.connect() # call the function again to try and connect to a different IP
raise (f"Error connecting {ex}")
The Idea is that I want to try a different IP if the first IP does not work. If there is any error then the Exception gets executed if the error count is <=1 and a different IP is added to the self.ip
and the connect()
function called again but it gives the following error:
[WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
CodePudding user response:
try:
...
self.conn.connect((self.ip, self.port))
return self.conn
except Exception as ex:
if self.error_count <=1:
...
self.connect() # call the function again to try and connect to a different IP
raise (f"Error connecting {ex}")
While you try to connect to a different IP address after the first failed, you ignore that this new connect succeeded and still raise the error from the initial connection fail.