networking.py 653 B

123456789101112131415161718
  1. import socket
  2. from contextlib import closing
  3. def get_free_port(params=(socket.AF_INET, socket.SOCK_STREAM), opt=(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)):
  4. """
  5. Finds a tcp port that can be occupied with a socket with *params and use *opt options.
  6. :note: Using this function is discouraged since it often leads to a race condition
  7. with the "Address is already in use" error if the code is run in parallel.
  8. """
  9. try:
  10. with closing(socket.socket(*params)) as sock:
  11. sock.bind(("", 0))
  12. sock.setsockopt(*opt)
  13. return sock.getsockname()[1]
  14. except Exception as e:
  15. raise e