how to know if socket is still connected

Grant Edwards grante at visi.com
Mon Jul 17 15:48:35 EDT 2006


On 2006-07-17, nephish at xit.net <nephish at xit.net> wrote:
>> If the server _application_ crashes or exits, then the OS will
>> close the socket and recv() will return "".  If somebody powers
>> down the server without warning, or if the server OS crashes,
>> or if the Ethernet cable between the Internet and the server is
>> cut, then the socket will not be closed, and recv() will wait
>> forever[1].
>
> Ok, yes all of the above is what i mean. Actually I am not too
> concerned about a server os crash, or the cable being cut. But I have
> had them close the connection on me, after which i just reconnect
> (whenever i discover that its happened)
>
>>[1] Unless you've enabled the TCP Keepalive feature, in which
>>    case the socket will timeout in a couple hours and recv()
>>    will return "".
>
> if this is something that must be enabled, or is not enabled by
> default, then it is not enabled.

On all OSes with which I'm familiar it's disabled by default.
You use a socket object's setsockopt method to enable it:

s.setsockopt(socket.SOL_TCP,socket.SO_KEEPALIVE,True)

-- 
Grant Edwards                   grante             Yow!  Wow! Look!! A stray
                                  at               meatball!! Let's interview
                               visi.com            it!



More information about the Python-list mailing list