title: How to close a socket left open by a killed program?
body: <p>I have a Python application which opens a simple TCP socket to communicate with another Python application on a separate host. Sometimes the program will either error or I will directly kill it, and in either case the socket may be left open for some unknown time.</p>
  
  <p>The next time I go to run the program I get this error:</p>
  
  <pre><code>socket.error: [Errno 98] Address already in use
  </code></pre>
  
  <p>Now the program always tries to use the same port, so it appears as though it is still open. I checked and am quite sure the program isn't running in the background and yet my address is still in use.</p>
  
  <p>SO, how can I manually (or otherwise) close a socket/address so that my program can immediately re-use it?</p>
  
  <p><strong>Update</strong></p>
  
  <p>Based on Mike's answer I checked out the <code>socket(7)</code> page and looked at SO_REUSEADDR:</p>
  
  <blockquote>
  <pre><code>SO_REUSEADDR
      Indicates that the rules used in validating addresses supplied in a bind(2) call should
      allow reuse of local addresses.  For AF_INET sockets this means that a socket may bind,
      except when there is an active listening socket bound to the address.  When the listen‐
      ing  socket is bound to INADDR_ANY with a specific port then it is not possible to bind
      to this port for any local address.  Argument is an integer boolean flag.
  </code></pre>
  </blockquote>