0

I am using this excellent answer to find a free port on python: https://stackoverflow.com/a/1365284/1467402

I want this method to pick me any free port, except for a single number. i.e, I want to get any free port except for 8000 since I am saving it for my application.

Is this possible using this method?

This is my code:

def get_free_port():
    import socket
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind(("",0))
    free_port = s.getsockname()[1]
    s.close
    return free_port

Thanks

Community
  • 1
  • 1
orizis
  • 166
  • 2
  • 15

1 Answers1

0

A bit of a hack, but what about binding to 8000, finding a free port, then closing the 8000 connection? – David

Armali
  • 18,255
  • 14
  • 57
  • 171
  • 1
    Hi, I didn't chose this method since I didn't want to bind and un-bind port for my purpose. Eventually I just checked if the port bind is what I wanted to avoid, and if so I am trying again. Haven't found anything better... – orizis Jun 21 '16 at 15:01