背景
自动注册服务时判断端口是否被占用
代码详情
import socket
def check_port(address, port):
# 创建套接字对象
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 检查端口是否占用
result = sock.connect_ex((address, port))
# 关闭套接字
sock.close()
# 返回结果
return result == 0
if __name__ == '__main__':
# 要检查的主机和端口
host = 'localhost'
port = 6379
# 检查端口占用情况
if check_port(host, port):
print(f'{host}:{port} 端口已被占用!')
else:
print(f'{host}:{port} 端口未被占用。')
check_port(host, port)
标签:__,socket,Python,占用,端口,host,port
From: https://blog.51cto.com/u_15222272/6210806