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

后端 未结 10 2230
小鲜肉
小鲜肉 2020-11-29 14:33

I\'m trying to set up a server with python from mac terminal.

I navigate to folder location an use:

python -m SimpleHTTPServer

Bu

相关标签:
10条回答
  • 2020-11-29 14:48

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

    0 讨论(0)
  • 2020-11-29 14:53

    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.

    0 讨论(0)
  • 2020-11-29 15:01

    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
    
    0 讨论(0)
  • 2020-11-29 15:03

    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()
    
    0 讨论(0)
  • 2020-11-29 15:03

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

    0 讨论(0)
  • 2020-11-29 15:04

    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.

    0 讨论(0)
提交回复
热议问题