Detecting socket connection failure

schwehr at gmail.com schwehr at gmail.com
Mon Jul 10 11:42:11 EDT 2006


Hi All,

I've tried to RTFM this and am having no luck.    First off, I am using
Mac OSX 10.4.7 with python 2.4.2 from fink.  I am trying to connect to
a server that should be rejecting connections and I was surprised when
it did not throw an exception or do something otherwise equally nasty.
It just connects and never returns any data.  First, the proof that
something is there and rejecting the connection (or is it that this
thing actually accepts the connection and then drops it?)...

telnet localhost 31414
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Connection closed by foreign host.


Now if I fire up ipython and try to connect...

In [1]: import socket, select

In [2]: remote = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

In [3]: remote.connect(('localhost',31414))

In [4]: remote.recv(200)
Out[4]: ''

In [5]: r,w,e=select.select([remote],[remote],[remote],1)

In [6]: print r,w,e
[<socket._socketobject object at 0x7e48d0>] [<socket._socketobject
object at 0x7e48d0>] []

In [7]: remote.recv(200)
Out[7]: ''

So it looks like it will for ever say that it is ready for read and
write, but really is not.  How do I detect this case?  The recv may
really not have any data for a long time, so a recv of no bytes is not
a way to test the connection status.  This is probably a FAQ, but I
can't figure it out.

Thanks!!
-kurt




More information about the Python-list mailing list