Search code examples
pythonlinuxcentosrhel

Python - error 98 Adress already in use, how to make it faster? So that on kill and quick restart it does not fail?


I have a Python protocol running under CentOS 6.4/64-bit. Where i am having TCP server port 7007. In some cases like update new version or maintenance or on the fly restart to refresh buffer i need to restart the application as:

server.py:

class AServer(threading.Thread):
  def __init__(self, port):
    threading.Thread.__init__(self)
    self.port = port

  def run(self):
    host = ''
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind((host, self.port))
    print bgcolors.BOOT
    s.listen(1)
    conn, addr = s.accept()
    print bgcolors.OK + 'contact', addr, 'on', self.now()

    while 1:
      try:
        data = conn.recv(1024)
      except socket.error:
        print bgcolors.OK + 'lost', addr, 'waiting..'
        s.listen(1)
        conn, addr = s.accept()
        print bgcolors.OK + 'contact', addr, 'on', self.now()
        continue
      if not data:
        ..... 
      ...

t = AServer(7007)
t.start()

Restart urgent on the fly (expecting to run within 1 second) but fails:

$ ps aux | awk '/server.py/ {print $2}' | head -1 | xargs kill -9;
$ nohup python /var/tmp/py-protocol/server.py &
[root@IPSecVPN protocol]# python server.py
Exception in thread Thread-1:
Traceback (most recent call last):
  File "/usr/lib64/python2.6/threading.py", line 532, in __bootstrap_inner
    self.run()
  File "server.py", line 236, in run
    s.bind((host, self.port))
  File "<string>", line 1, in bind
error: [Errno 98] Address already in use

Solution

  • Your socket is in the TIME_WAIT state which is why the address is still in use even though your program has quit. You can set SO_REUSEADDR on the socket to reuse it before the sockets exits the TIME_WAIT state. The Python documentation suggests the following:

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind((HOST, PORT))