Search code examples
pythonbottle

How to make Bottle return an error if a port is already being listened to?


I'm working based on Bottle's "Hello World" example, which can be found here: https://bottlepy.org/docs/dev/tutorial.html

from bottle import Bottle, run

app = Bottle()

@app.route('/hello')
def hello():
    return "Hello World!"

run(app, host='localhost', port=8080)

My problem is that this code can be run multiple times and then only the first instance will be the one actually doing the serving. Is it possible to make the program return an error to indicate that the port is already being listened to?


Solution

  • Quick and dirty check to see if a port is open before running your bottle application could be useful.

    import socket
    
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    
    try:
        s.bind(("127.0.0.1", 8000))
    s.close()
    

    Code above will try to bind to socket 8000 on localhost and will fail if the socket is already in use returning a 48 error Address already in use. If it succeeds then it'll close (unbind) port 8000.