Skip to content

Instantly share code, notes, and snippets.

@liuqinh2s
Created June 24, 2019 07:16
Show Gist options
  • Save liuqinh2s/91875992d2c9fc54e5483b9a0c2cd50f to your computer and use it in GitHub Desktop.
Save liuqinh2s/91875992d2c9fc54e5483b9a0c2cd50f to your computer and use it in GitHub Desktop.
def findFreePort():
"""
函数返回值是当前可用来监听的一个随机端口。
"""
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('localhost', 0))
# 用getsockname来获取我们实际绑定的端口号
addr, port = s.getsockname()
# 释放端口
s.close()
return port
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment