I'm writing a network application, and have been running into a slight nuisance. I have to wait a period in-between tests, because my server program, even after closing still has the port I'm using "allocated" to it. Furthermore, this makes debugging really hard, since I can't tell what's causing whatever problem I'm dealing with.

For testing purposes, is there a way to free up TCP and UDP ports?


In your python program you need to call the shutdown and close functions for the socket to let the OS know that your program is no longer using it and it will deallocate the socket if nothing is using it after calling those functions. If you fail to call these functions when your program exits, you will end up having to wait on the OS to clean up stale allocated sockets. Even if you force kill the application as the OS still doesn't have a way to know explicitly that its not being used. So, when a program dies and it doesn't close the socket properly, the OS will keep it allocated for a bit of time, until it does its check to see if it is indeed being used, and if it isn't it then deallocates it for use by other programs.

Here is a link that will explain the shutdown and close functions for sockets in python. SO Answer

  • Thank you for the link, but this isn't quite what I'm asking for. Maybe I wasn't clear, but I need this for debugging. If the program crashes before the shutdown or close functions can be called, then I still have this problem. – Charles Noon Aug 10 '16 at 2:33
  • The answer is there but let me clarify it for you. If your program exits in an ungraceful manner. IE, it crashes, it gets forced killed, or it never calles the appropriate functions before closing. You will be forced to wait for the OS to do its clean up of stale sockets. Which is about a minute or so. Here is another link that details it more in depth about the problem you are having and why it exists and why you can't just deallocate a socket yourself outside the owning program that created the socket and the OS does it. superuser.com/a/127865/627762 – Frostalf Aug 10 '16 at 2:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.