How to tell when a socket is closed on the other end?
roy at panix.com
Wed Jul 25 16:37:00 CEST 2007
In article <1185371863.622473.205010 at 19g2000hsx.googlegroups.com>,
billiejoex <gnewsg at gmail.com> wrote:
> Hi there.
> I'm setting up test suite for a project of mine.
> >From test suite, acting as a client, I'd like to know, in certain
> situations, if the socket is closed on the other end or not.
> I noticed that I can "detect" such state if a call to socket.read()
> returns 0 but it seems a little poor to me. :-\
> Is there a reliable way to test such socket 'state'?
This isn't really a Python question, it's a Berkeley Socket API question.
You don't say, but I assume you're talking about a TCP (i.e. SOCKSTREAM)
The answer is you can use the select() system call to detect "exceptional
conditions" on a socket. Python's select module provides this
functionality, but to understand how to use it, you need to study the
On the other hand, socket.read() returning 0 works too. What do you find
"poor" about that? What do you want to know about the connection being
closed that you don't find out by getting 0 back from read()?
More information about the Python-list