I have a python code that connects to IMAP server via IMAP4_SSL, and everything works fine until it tries to close the connection with this:
def logout(self):
"Close the mailbox and logout and set the connection to None"
try:
self.connection.close()
self.connection.logout()
except e:
pass
self.connection = None
This leaves the connection in CLOSE_WAIT state:
tcp 38 0 1.2.3.4:55809 5.6.7.8:993 CLOSE_WAIT 18983/python2.6
Where it remains for a prolonged time. The python process itself is a long-running daemon that does IMAP checks periodically, so these accumulate with time. Any ideas why it might be happening and what I am doing wrong?
Sockets hang out in CLOSE_WAIT when they haven’t been closed by the local program.
Looking at the imaplib source, the only place that
self.sock.close()is called is inshutdown().My guess is you need to call
self.connection.shutdown().update: As Bruno notes,
logout()callsshutdown(). However, the way the example code is structured, ifclose()raises an exeception thenlogout()will be silently skipped… andshutdown()won’t be called. I wonder if that’s what’s going on.