pifpaf icon indicating copy to clipboard operation
pifpaf copied to clipboard

Choose a random free port

Open felixonmars opened this issue 8 years ago • 5 comments

It would be nice to have an option to choose a random free port, and the target program can read it from environment variables.

felixonmars avatar Aug 06 '16 09:08 felixonmars

Agreed, it's actually on my TODO list. It's pretty hard to "find a random available port" because there's a big race between the time you find the free port and the time the program binds it.

It seems the best way would be to be able to provide a port range to pifpaf that you are sure are available, no matters what.

jd avatar Aug 06 '16 12:08 jd

I prefer to bind a loopback interface 127.0.0.0/8 (according to the RFC 1700) and always keep the same port. It works on Linux, Windows (loopback adapter) and MacOS

On MacOS you must declare the new loopback interface manually like sudo ifconfig lo666 alias 127.6.6.6 and to remove it sudo ifconfig lo666 -alias 127.6.6.6

I use this tips to launch multiple versions of PostgreSQL server with loopback that containt the version number in the loopback address and port 5432 like:

  • 127.0.9.3 for PostgreSQL 9.3
  • 127.0.9.4 for PostgreSQL 9.4
  • 127.0.9.5 for PostgreSQL 9.5

kryskool avatar Aug 06 '16 15:08 kryskool

@kryskool This is a good idea, but it's gonna be tricky if it's not portable out of the box on Darwin :(

jd avatar Aug 06 '16 16:08 jd

can you not listen on port 0? then ask the program what port it found?

graingert avatar Sep 26 '19 12:09 graingert

@jd it might be good to use https://github.com/Yelp/ephemeral-port-reserve/

graingert avatar Feb 01 '21 13:02 graingert