Wednesday, July 20, 2005

on Broken Pipe and Connection Reset By Peer

Maybe I'm just dumb, but I always thought "broken pipe" meant, "the other end of this socket closed before I finished sending something" and "connection reset by peer" meant, well, roughly the same thing. (As well as indicating some slightly more esoteric problems.)

Turns out though, "broken pipe" actually means "I just tried to send something and the socket was already closed to sending."

So in the following example, if the other end of (TCP) socket "sock" closes or dies before the write method, "connection reset by peer" will be raised. The next write will give a broken-pipe error, since the socket now knows that further sending is invalid.

try:
    sock.write('foo')
except:
    pass # connection reset by peer
sock.write('bar') # broken pipe

1 comment:

Tim Lesher said...

The late W. Richard Stevens' books are an excellent resource for these issues. The first two volumes of TCP/IP Illustrated should be required reading for network programmers, and the first volume of UNIX Network Programming (The Sockets Networking API) isn't far behind on the list.

Even if you never hand-assemble or disassemble a packet in your life, knowing what's under the hood helps when you see a curiosity like this.

Volume three of TCP/IP Illustrated deals with TTCP, a transaction-oriented protocol based on TCP that never really gained much acceptance. Reading it is interesting as a design exercise--while you're unlikely to run across TTCP in the field, the design issues are common ones.