Article directory
1. Idea
When using like socket
modules, when the port number needs to be bound, if the port number is occupied, it will cause a port number conflict.
For frequently used port numbers that cause port number conflicts, the solution can be to automatically obtain a non-conflicted port number and bind this port number.
The idea is as follows:
- Write a
get_port.py
script that encapsulates a function insideget_port()
. Each time the function is called, a new port number will be obtained, and the port number will increase by one. get_port()
The obtained port number is given a range[initPort, endPort]
. In order to avoid port number conflicts, this range does not include the existing port numbers on the machine.- After walking from
initPort
to toendPort
, reset the port number toinitPort
, and reuse the port number to avoid infinite increment of the obtained port number.
2. Code implementation
Create a new get_port.py
file with the following content:
import os
portFile = 'port.txt' # 端口号文件
initPort = '10001' # 初始端口号
endPort = '10010' # 结束端口号
# 创建端口号文件,并写入初始端口号
def create_port_file():
with open(portFile, 'w') as f:
f.write(initPort)
# 获取端口号
def get_port():
if not os.path.exists(portFile): # 端口号文件不存在则创建
create_port_file()
with open(portFile, 'r') as f:
port = f.read()
update_port(port)
if port == endPort: # 重置端口号
create_port_file()
print("The current port number: {}".format(port))
return int(port)
# 更新端口号
def update_port(oldPort):
newPort = int(oldPort) + 1
with open(portFile,'w') as f:
port = f.write(str(newPort))
if __name__ == "__main__":
for i in range(15):
get_port()
The result of the operation is as follows:
The current port number: 10001
The current port number: 10002
The current port number: 10003
The current port number: 10004
The current port number: 10005
The current port number: 10006
The current port number: 10007
The current port number: 10008
The current port number: 10009
The current port number: 10010
The current port number: 10001
The current port number: 10002
The current port number: 10003
The current port number: 10004
The current port number: 10005
3. Port number usage
Create a new one in get_port.py
the same directory test.py
, import the get_port
module, and use get_port()
the function.
test.py
The content of the file is as follows:
import socket
from get_port import get_port # 导入get_port模块
s = socket.socket() # 创建socket对象
host = socket.gethostname() # 获取本地主机名
port = get_port() # 使用get_port模块的get_port()函数
s.bind((host, port)) # 绑定端口