Kakarot
Kakarot

Reputation: 195

Flask allows multiple server instances to listen on the same port

I have been using flask and noticed this unusual behavior.

My flask application is set to run on port 5000 in my machine (It has only one network card).

When I attempt to start more than one instance of the same flask application in my machine.

What I Expected:

A port address in use error when attempting to start the next instance bound on the same port.

What actually happened:

They all start successfully and bind to the same port. This kind of behavior is not expected with most conventional servers that I have used. Thankfully however, only one process out of the 'n' processes is triggered when a REST API call is made to the server.

Operating System: Windows

Can someone please explain why this behavior occurs, and how can I ensure that flask doesn't start the process successfully in such a case.

netstat -aon | find "5000"

TCP 127.0.0.1:5000 0.0.0.0:0 LISTENING 37036
TCP 127.0.0.1:5000 0.0.0.0:0 LISTENING 5024
TCP 127.0.0.1:5000 0.0.0.0:0 LISTENING 61684

The above are the 3 process that are running in parallel.

Additional Notes:

  1. I am using this in a virtualenv.
  2. The way I have written my flask invocation.

    if __name__ == "__main__":
    main()
    app.run(port=5000)
    
  3. Running the code as python3 <filename>.py at the command prompt.

Upvotes: 6

Views: 3103

Answers (1)

nberrios
nberrios

Reputation: 51

This is likely Windows specific behavior and how they manage sockets. On Windows, you can have multiple processes bind to the same port for listening. This was found to cause a lot of security issues, so Windows released updates that can prevent a port from being hi-jacked by another process via the SO_EXCLUSIVEADDRUSE socket flag. You can read more about it at https://learn.microsoft.com/en-us/windows/desktop/winsock/so-exclusiveaddruse

From what I can see by reading through the flask development server code, there is no way for a user to set the SO_EXCLUSIVEADDRUSE flag.

Upvotes: 5

Related Questions