ユニットテストで一時的なサーバプロセスを立ち上げたりする際にポート番号がバッティングしないようにしたかった。
psutil
パッケージを使用する。
$ pip install psutil
import psutil
def unused_portnumber(start=49152):
# "LISTEN" 状態のポート番号をリスト化
used_ports = [conn.laddr.port for conn in psutil.net_connections() if conn.status == 'LISTEN']
for port in range(start, 65535 + 1):
# 未使用のポート番号ならreturn
if port not in set(used_ports):
return port
ちなみにRFCによると ダイナミック/プライベートポート番号の割当ては49152番以降らしい。