Detecting shutdown of remote socket endpoint.

Tim Gosselin gosselit at norwich.edu
Tue Jan 11 18:40:36 EST 2005


I am writing a tcp tunnel but cannot find a way of detecting when a socket
shuts down its read end without writing to the socket. For testing the
write end of the remote endpoint I just do a:

if not sock.recv(buffsize)

I cannot write to the socket and check if send returns 0 though, because
that involves sending data out of the which may not have come in yet.

When I try polling the socket with:
r, w, e=select([],[sock],[], 0)
w returns with the socket still writable, even if the other end was
closed.

#For example:
s=socket()
s.bind(('localhost', 5000))
s.listen(5)
s2, addr=s.accept()

#then create a socket to connect,
s=socket()
s.connect(('localhost', 5000))

#then I close the server side,
s2.close() #or s2.shutdown(0)

#and poll s to see if it's still writable,
r, w, e=select([],[s],[], 0)
#this returns that the socket is writable! and i can even write to it,
s.send('test') #succeeds
#but the second write finally throws an exception.

Is there any other way to check if a the remote endpoint on a socket has
shutdown its read end? Is it difficult to implement a sock.is_shutdown(1)
with some additional c code?



More information about the Python-list mailing list