I'm trying to set up a server with python from mac terminal.
I navigate to folder location an use:
python -m SimpleHTTPServer
But this gives me error:
socket.error: [Errno 48] Address already in use
I had previously open a connection using the same command for a different website in a different location in my machine.
Use
This will give you a list of processes using the port if any. Once the list of processes is given, use the id on the PID column to terminate the process use
You can also serve on the next-highest available port doing something like this in Python:
If you need to do the same thing for other utilities, it may be more convenient as a bash script:
Set that up as a executable with the name
get-free-port
and you can do something like this:That's not as reliable as the native Python approach because the bash script doesn't capture the port -- another process could grab the port before your process does (race condition) -- but still may be useful enough when using a utility that doesn't have a try-try-again approach of its own.
I am new to Python, but after my brief research I found out that this is typical of sockets being binded. It just so happens that the socket is still being used and you may have to wait to use it. Or, you can just add:
This should make the port available within a shorter time. In my case, it made the port available almost immediately.
Just in case above solutions didn't work:
Get the port your process is listening to:
$ ps ax | grep python
Kill the Process
$ kill PROCESS_NAME
I have a raspberry pi, and I am using python web server (using Flask). I have tried everything above, the only solution is to close the terminal(shell) and open it again. Or restart the raspberry pi, because nothing stops that webserver...
By the way, to prevent this from happening in the first place, simply press Ctrl+C in terminal while SimpleHTTPServer is still running normally. This will "properly" stop the server and release the port so you don't have to find and kill the process again before restarting the server.
(Mods: I did try to put this comment on the best answer where it belongs, but I don't have enough reputation.)