socket.error: [Errno 48] Address already in use
Asked Answered
S

16

322

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.

Sollows answered 28/9, 2013 at 20:48 Comment(3)
Kill the other process or run this one with a different port: python -m SimpleHTTPServer 8081Outlaw
This is a symptom that can be caused by many conditions. I recommend using the answers below as a troubleshooting guide not as a set of "answers", the votes representing the popularity of the troubleshooting path.Phifer
Related question: in the case where the port is not used by any process and is in TIME_WAIT state, refer to linux - Python [Errno 98] Address already in use - Stack Overflow . ■ See also unix - How to kill a process running on particular port in Linux? - Stack Overflow for more ways to kill process running on a port.Mecke
C
467

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.

Cotidal answered 28/9, 2013 at 20:54 Comment(5)
What url should I have in browser to see if it is working? I'm running on a different port as you sugestedSollows
might need to use sudo kill -9 PIDChancery
Thanks, @Danpe, I tried "sudo kill PID" which didn't work but "sudo kill -9 PID" killed the process. Anyone know what -9 specifies? Even sudo manual doesn't seem to cover this parameter sudo.ws/man/sudo.man.htmlBaryton
@seokhoonlee: kill sends a signal to the process, which it can decide to handle (like shut down gracefully or rotate a logfile). These signals are integers (each with a name), the default being 15, meaning TERM or terminate. Using -9 sends signal 9, KILL, which a process can't catch and ignore, and the OS will end the process wether it likes to or not.Cotidal
@seokhoonlee: also see the Unix signal article on Wikipedia.Cotidal
H
306

Simple solution:

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

kill -9 $PID  //to forcefully kill the port

PID is got from step 1's output.

Hilaire answered 18/9, 2016 at 11:28 Comment(6)
This answer would benefit from an example of what the lsof output might look like, and how to find the process ID (the "XXXX" you list) within the output. For anyone seeing this without that information, it's the second field in the output, under a header label of "PID".Nereen
@CarlosRodríguez I want to believe he found your response absolutely on point. I think your observation on the need to give samples of the output of lsof and how to identify PID is very important. The second item in each row returned is usually the PID, it is always under the PID column of the outputTeplitz
what does -9 mean?Boredom
@Boredom the -9 is the shoter format for -KILL --> with kill command you can specify some signal and -KILL or -9 is one of the signals...Beer
Still works in 2022. I am using Macbook pro 14.Oleg
Not really sure why that needs sudo...Lights
C
56

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
Cuvette answered 5/5, 2017 at 13:56 Comment(2)
That's perfect, especially those working on MAC OSX and didn't use SO_REUSEPORT instead of SO_REUSEADDRPaxwax
This answer solved my issue. I could not access the localhost at port 5000 with an error (this site can’t be reached localhost refused to connect)Adiabatic
S
34

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

Swirl answered 17/1, 2019 at 9:47 Comment(1)
Working on MacOSX (i do not know if that is relevant), but I had to use the "-9" argument to make it work. This is the only answer that mentions that.Afforest
M
25

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.

Mella answered 14/10, 2016 at 11:56 Comment(1)
Useful info here, I was pressing Ctrl+Z unconciously and the process got kept alive. Ctrl+C releases the port so no need to manually kill it.Strabismus
C
13

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()
Cleareyed answered 29/10, 2019 at 16:32 Comment(1)
The property must be set on the class and not the object/instance, before instantiating it: SocketServer.TCPServer.allow_reuse_address = True (from https://mcmap.net/q/100935/-python-tcpserver-address-already-in-use-but-i-close-the-server-and-i-use-allow_reuse_address ). It is probably cleaner to inherit TCPServer to a new class and set the value there.Damaraland
D
8

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.

Disaster answered 21/9, 2015 at 14:31 Comment(0)
B
7

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.

Breton answered 26/3, 2018 at 4:1 Comment(1)
No imports? Just like that?Hummock
V
7

Case with me

This happens when I debug or run a server and when done, instead of Terminating the process, I Disconnect it.

PyCharm asks for these two options when we try to close it while the server is still running

This results that, the process still running in the background on that particular address, hence, Address already in use error.

Solution

pkill python

Works for me.

Another Case - Multiple Processes

If you have more than one server/application running with python (obviously, at different ports 😅), then get the PID of that process using PORT and kill it.

sudo lsof -i :5000 # here 5000 is the port number  

| COMMAND | PID    | USER     | FD | TYPE | DEVICE | SIZE/OFF | NODE | NAME                    |
|---------|--------|----------|----|------|--------|----------|------|-------------------------|
| python  | 185339 | username | 7u | IPv4 | 598745 | 0t0      | TCP  | localhost:5000 (LISTEN) |
| python  | 185348 | username | 7u | IPv4 | 598745 | 0t0      | TCP  | localhost:5000 (LISTEN) |
| python  | 185350 | username | 8u | IPv4 | 598745 | 0t0      | TCP  | localhost:5000 (LISTEN) |


kill -9 185339 # here 185339 is the PID from above output; keep the -9 as it is

Check @Andrew's answer to prevent this in future.

References: kill command, kill/pkill/killall, lsof

Namaste 🙏

Ventris answered 26/4, 2021 at 12:55 Comment(0)
M
5

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

Mortar answered 23/7, 2018 at 5:20 Comment(0)
B
3

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

Bentonbentonite answered 26/7, 2018 at 9:21 Comment(0)
M
2

Explanation

Generally speaking, there are 2 common causes for this:

  • Some other server process is running, and already bound to that port.
  • No process is bound to the port, however the port is in TIME_WAIT state.

Determine which one is the case

From now on, assume the port is 8000.

There are different ways. Run one of the following 2, if it's nonempty then it's case 1, otherwise it's case 2.

  • lsof -i :8000
  • fuser 8000/tcp (or fuser 8000 --namespace tcp)

Remark: what is irdmi (or http-alt, etc.)?

It just mean 8000 or 8080. Refer to https://serverfault.com/questions/321823/how-to-stop-irdmi-when-running-nginx#321825 .

From man services: "services is a plain ASCII file providing a mapping between human‐friendly textual names for internet services, and their underlying assigned port numbers and protocol types."

Case 1. Some program is running

There are different ways.

Case 2. No program is running, socket in TIME_WAIT state

There are different ways.

Print out the sockets in TIME_WAIT state

The following method will print both the listening socket and the possible TIME_WAIT connection.

How to avoid the problem in the first place

This only applies if you are encountering case 2, and the offending program (that previously used that port) is written by you.

Use SO_REUSEADDR option.

Extra: Explanation, miscellaneous note

Refer to this answer for explanation why TIME_WAIT state exist.

In order to reproduce the problem, you need a client to connect to the server before killing the server.

See also How do SO_REUSEADDR and SO_REUSEPORT differ? .

Extra: change the duration of TIME_WAIT

Not a recommended method.

Mecke answered 1/11, 2023 at 3:46 Comment(0)
H
1

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
Harryharsh answered 19/2, 2021 at 18:41 Comment(0)
B
0

Adding to the answer from Michael Schmid Just had the problem, to allow rebinding of the port use needs to SUBCLASS the socket server like this:

from socketserver import TCPServer, BaseRequestHandler
from typing import Tuple, Callable
class MySockServer(TCPServer):
    def __init__(self, server_address: Tuple[str, int], RequestHandlerClass: Callable[..., BaseRequestHandler]):
        self.allow_reuse_address = True
        super().__init__(server_address, RequestHandlerClass)

because after instantiation, there is not point in changing that flag. Then use it instead of TCPServer or whatever you are using.

Bloodstone answered 1/3, 2021 at 10:11 Comment(0)
P
0

This error is returned because an attempt is made to rerun the project while it is still running. Stop and restart the project.

Pluralize answered 8/1, 2022 at 12:47 Comment(0)
M
0

the only solution that worked for me was restarting my laptop.

Modernism answered 15/3, 2023 at 19:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.