Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python socket stays CLOSE_WAIT

Tags:

python

sockets

i have an application which listen on sockets. this application is monitored by nagios. the problem is, that nagios opens sockets and closes those directly.My application sockets stays in CLOSE_WAIT. And i dont understand why this happens. It should run into an error and kill the socket.

           while request=="":
                    try:
                            request = self.client.recv ( 1024 ).rstrip()
                    except socket.timeout, msg:
                                    log.error( "no request")
                                    self.client.close()
                                    return
                    except socket.error, msg:
                                    print msg
                                    self.client.close()
                                    return
                    except msg:
                                    log.error(msg)
                                    self.client.close()
                                    return

Any ideas how to catch this properly?

like image 985
user1010775 Avatar asked Sep 26 '26 11:09

user1010775


2 Answers

CLOSE_WAIT state means that the socket is expected to be closed by the application.

In the code you posted the socket is only closed on exception. Make sure you close the socket when it receives EOF, i.e. check for not request before stripping it.

like image 185
Maxim Egorushkin Avatar answered Sep 30 '26 01:09

Maxim Egorushkin


When connection is gracefully closed by remote side, the standard BSD recv call returns zero. In Python, the returned value is translated to empty string. In both cases it's not considered as an error, so you shouldn't expect any exceptions.

Your code can say:

request = self.client.recv(1024).rstrip()
if not request:
  print "Connection closed"
  self.client.close()

You can also close the connection in finally block after your try-except blocks to avoid code duplication. If you expect the server to close the connection after sending the data, you could express it as follow:

request = ""
r = True
while r:
  r = self.client.recv(1024)
  request += r
like image 37
tomasz Avatar answered Sep 29 '26 23:09

tomasz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!