Welcome, guest | Sign In | My Account | Store | Cart

Picking an unused port is easy to do using the socket module.

Python, 8 lines
1
2
3
4
5
6
7
8
import socket

def PickUnusedPort():
  s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  s.bind(('localhost', 0))
  addr, port = s.getsockname()
  s.close()
  return port

1 comment

Raghuram Devarakonda 16 years, 7 months ago  # | flag

port is not guaranteed to be free. I have been using similar code for a while and it is very useful. How ever, for the sake of completeness, you should point out that there is small window where port can be taken by some other process. - Raghu

Created by Damon Kohler on Wed, 19 Sep 2007 (PSF)
Python recipes (4591)
Damon Kohler's recipes (1)

Required Modules

Other Information and Tasks