2
4

More than 3 years have passed since last update.

PythonでOSの空きポート番号を取得する

Posted at

ユニットテストで一時的なサーバプロセスを立ち上げたりする際にポート番号がバッティングしないようにしたかった。

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番以降らしい。

2
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
4