[python] socket.error: [Errno 48] Address already in use

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.

This question is related to python macos simplehttpserver

The answer is


You already have a process bound to the default port (8000). If you already ran the same module before, it is most likely that process still bound to the port. Try and locate the other process first:

$ ps -fA | grep python
  501 81651 12648   0  9:53PM ttys000    0:00.16 python -m SimpleHTTPServer

The command arguments are included, so you can spot the one running SimpleHTTPServer if more than one python process is active. You may want to test if http://localhost:8000/ still shows a directory listing for local files.

The second number is the process number; stop the server by sending it a signal:

kill 81651

This sends a standard SIGTERM signal; if the process is unresponsive you may have to resort to tougher methods like sending a SIGKILL (kill -s KILL <pid> or kill -9 <pid>) signal instead. See Wikipedia for more details.

Alternatively, run the server on a different port, by specifying the alternative port on the command line:

$ python -m SimpleHTTPServer 8910
Serving HTTP on 0.0.0.0 port 8910 ...

then access the server as http://localhost:8910; where 8910 can be any number from 1024 and up, provided the port is not already taken.


Simple solution:

  1. Find the process using port 8080:
`sudo lsof -i:8080`
  1. Kill the process on that port:
`kill $PID`

PID is got from step 1's output.


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...


This commonly happened use case for any developer.

It is better to have it as function in your local system. (So better to keep this script in one of the shell profile like ksh/zsh or bash profile based on the user preference)

function killport {
   kill -9 `lsof -i tcp:"$1" | grep LISTEN | awk '{print $2}'`
}

Usage:

killport port_number

Example:

killport 8080

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.)


Use

 sudo lsof -i:5000

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

 kill 379 #use the provided PID

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:

tcpSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

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:

  1. Get the port your process is listening to:

    $ ps ax | grep python

  2. Kill the Process

    $ kill PROCESS_NAME


Simple one line command to get rid of it, type below command in terminal,

ps -a

This will list out all process, checkout which is being used by Python and type bellow command in terminal,

kill -9 (processID) 

For example kill -9 33178


You can also serve on the next-highest available port doing something like this in Python:

import SimpleHTTPServer
import SocketServer

Handler = SimpleHTTPServer.SimpleHTTPRequestHandler

port = 8000
while True:
    try:
        httpd = SocketServer.TCPServer(('', port), Handler)
        print 'Serving on port', port
        httpd.serve_forever()
    except SocketServer.socket.error as exc:
        if exc.args[0] != 48:
            raise
        print 'Port', port, 'already in use'
        port += 1
    else:
        break

If you need to do the same thing for other utilities, it may be more convenient as a bash script:

#!/usr/bin/env bash

MIN_PORT=${1:-1025}
MAX_PORT=${2:-65535}

(netstat -atn | awk '{printf "%s\n%s\n", $4, $4}' | grep -oE '[0-9]*$'; seq "$MIN_PORT" "$MAX_PORT") | sort -R | head -n 1

Set that up as a executable with the name get-free-port and you can do something like this:

someprogram --port=$(get-free-port)

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.


You can allow the server to reuse an address with allow_reuse_address.

Whether the server will allow the reuse of an address. This defaults to False, and can be set in subclasses to change the policy.

import SimpleHTTPServer, SocketServer
PORT = 8000
httpd = SocketServer.TCPServer(("", PORT), SimpleHTTPServer.SimpleHTTPRequestHandler)
httpd.allow_reuse_address = True
print "Serving at port", PORT
httpd.serve_forever()

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to macos

Problems with installation of Google App Engine SDK for php in OS X dyld: Library not loaded: /usr/local/opt/openssl/lib/libssl.1.0.0.dylib dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac Could not install packages due to an EnvironmentError: [Errno 13] How do I install Java on Mac OSX allowing version switching? Git is not working after macOS Update (xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools) Can't compile C program on a Mac after upgrade to Mojave You don't have write permissions for the /Library/Ruby/Gems/2.3.0 directory. (mac user) How can I install a previous version of Python 3 in macOS using homebrew? Could not install packages due to a "Environment error :[error 13]: permission denied : 'usr/local/bin/f2py'"

Examples related to simplehttpserver

socket.error: [Errno 48] Address already in use Set up Python simpleHTTPserver on Windows What is a faster alternative to Python's http.server (or SimpleHTTPServer)? How do I shut down a python simpleHTTPserver? What is the Python 3 equivalent of "python -m SimpleHTTPServer"