Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 'Connection reset by peer'

I'm playing around with Python and listening for UDP packets on a given port, everything seems to be working nicely - but after an extended period of time the script crashes with the following error:

data = self._sock.recv(self._rbufsize)
socket.error: [Errno 54] Connection reset by peer

When restarting just the script, the same crash occurs again after a shorter period of time. Restarting the server instead seems to resolve the problem completely for a while again.

With respect to the socket side of things, I'm doing:

UDP_IP = "0.0.0.0"
UDP_PORT = 6000

sock = socket.socket( socket.AF_INET, socket.SOCK_DGRAM )
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind( (UDP_IP, UDP_PORT) )

Am I missing something obvious or is there just a simple way of avoiding this?

Thanks in advance for any light you can shed!

Benji

like image 527
Benji Barash Avatar asked Aug 27 '12 09:08

Benji Barash


1 Answers

The error "Connection reset by peer" on a UDP socket, means the client has received an ICMP error message (for example: port unreachable, TTL exceeded, etc.) from the server on a packet it has sent.

I can't say for sure what is causing this in your code, but I can offer two ideas:

  1. The connection was really interrupted by something (routing problem, server side failure, etc.). In this case, you can check for this error, and if and when it occurs you can reopen your socket.
  2. What seems more probable to me, but I'm less familiar with, is that SO_REUSEADDR is causing the problem. This socket option lets you open multiple sockets on the same port. What possibly happens, is that some other process is trying to use port 6000, succeeds (because you tell the OS not to block it), and your socket is closed by the OS. Since I don't see a reason to use SO_REUSEADDR on UDP sockets, I would suggest you remove the line sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) and try again.

Best of luck!

like image 147
Oded R. Avatar answered Oct 17 '22 20:10

Oded R.