Python handling socket.error: [Errno 104] Connection reset by peer Python handling socket.error: [Errno 104] Connection reset by peer python python

Python handling socket.error: [Errno 104] Connection reset by peer


"Connection reset by peer" is the TCP/IP equivalent of slamming the phone back on the hook. It's more polite than merely not replying, leaving one hanging. But it's not the FIN-ACK expected of the truly polite TCP/IP converseur. (From other SO answer)

So you can't do anything about it, it is the issue of the server.

But you could use try .. except block to handle that exception:

from socket import error as SocketErrorimport errnotry:    response = urllib2.urlopen(request).read()except SocketError as e:    if e.errno != errno.ECONNRESET:        raise # Not error we are looking for    pass # Handle error here.


You can try to add some time.sleep calls to your code.

It seems like the server side limits the amount of requests per timeunit (hour, day, second) as a security issue. You need to guess how many (maybe using another script with a counter?) and adjust your script to not surpass this limit.

In order to avoid your code from crashing, try to catch this error with try .. except around the urllib2 calls.


There is a way to catch the error directly in the except clause with ConnectionResetError, better to isolate the right error.This example also catches the timeout.

from urllib.request import urlopen from socket import timeouturl = "http://......"try:     string = urlopen(url, timeout=5).read()except ConnectionResetError:    print("==> ConnectionResetError")    passexcept timeout:     print("==> Timeout")    pass