#897·ctf-wiki

添加一个指定端口号的方法,以避免端口占用

作者: cnzyan创建于 2024年5月11日更新于 2024年9月29日

Modify the docs.py file to add the following at the beginning: import sys import socket import subprocess import platform def check_port_in_use(port): system = platform.system() print(f"Trying to check the port using socket: {port}") check_dict = {} is_port_in_use = False try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(('localhost', port)) sock.close() check_dict["Socket"] = False except socket.error: print(f"The socket check failed to use the port number {port}, it may be occupied.") check_dict["Socket"] = True is_port_in_use = True # If a socket error occurs, mark the port as occupied. return check_dict, is_port_in_use If there are more than two arguments in sys.argv, the port number is the last one. If there are fewer than two arguments, the default port number is 8008. If the port number is not a digit, the default port number is 8008. If check_port_in_use(int(port_num))[1] is True, it means the port is occupied. In this case, the script will try to use another port. For example, if the port is 8008, the script will try to use port 8009. If the script cannot find a free port, it will use the default port 8008.

内容来源: ctf-wiki/ctf-wiki