I'm using python's telnetlib to connect to a remote telnet server. I'm having a hard time detecting if the connection is still open, or if the remote server closed it on me.
I will notice the connection is closed the next time I try to read or write to it, but would like to have a way to detect it on demand.
Is there a way to send some sort of an 'Are You There' packet without affecting the actual connection? The telnet RFC supports an "are you there" and "NOP" commands - just not sure how to get telnetlib to send them!
Following up on David's solution, after
close()
on the interface, thesock
attribute changes from being asocket._socketobject
to being the integer 0. The call to.sendall
fails with anAttributeError
if the socket is closed, so you may as well just check its type.Tested with Linux and Windows 7.
You should be able to send a NOP this way:
I've noticed that for some reason sending only once was not enough ... I've "discovered it" by accident, I had something like this:
after a few runs I've noticed that the log message was saying "is alive True", but the code didn't entered the "if", and that the log message "telnet send failed - dead" was printed, so in my last implementation, as I was saying here, I'm just calling the
.send()
method 3 times (just in case 2 were not enough).That's my 2 cents, hope it helps