logIt Log Around The Clock

Close Low Level Socket in Python

tags:

Important to do in socket programming is to close the socket. Python.org says

Close the socket. All future operations on the socket object will fail. The remote end will receive no more data (after queued data is flushed). Sockets are automatically closed when they are garbage-collected.

I implemented this low level networking interface for a server listening to remote command. The complete code can be found on Github, the following lines are just part to show when to close socket:

43
44
45
46
        clientSocket,address =s.accept()
        data = clientSocket.recv(1024)
        print "Receive command:"+data
        clientSocket.close()

What happened with the TCP state when the socket wasn’t closed: it stayed in CLOSE_WAIT state. The screenshot below shows a clip of the TCP conversation in Wireshark sniff and the netstat output:

Listening port state of a socket server written in Python


Leave a Reply