Shammer's Philosophy

My private adversaria

Python most basic FIN handling

Almost computer languages can handle socket that enables connecting other hosts or listening from other hosts. And a user should master how to handling sockets via those APIs, like opening a listen port, connecting other hosts, closing socket correctly.
I wrote about the way how to open a listening port and how to connect other hosts in those articles before.

But the way opening sockets is very simple, there is almost nothing which should be considered. But, the way how to close them is not simple. There are a lot of cases. For example, what is the correct way when clients send RST while the server is sending a response? Is there any way that sending FIN packets without any problems? There is no such way so sometimes CLOSE_WAIT sockets remained unexpectedly.
Those cases are not only one pattern, it is impossible to describe all of them. But I want to organize the basic way hot to close sockets correctly. More strictly saying, I want to organize more clear what kind of data would be read via API. For example, what kind of data received via python recv() when clients send FIN packets? The answer is '', the sample code is like below.

import socket
server = socket.socket(socket.AF_INET)
server.bind(('localhost',7001))
server.listen(1)
while True:
  try:
    client, addr = server.accept()
    data = client.recv(1)
    if data == '':
      print 'FIN received from client.'
      client.close()
...

I think this is the most basic pattern and all socket programmers have to know. On python, recv() returns '' when peer sockets send FIN.