废话不多说直接上代码
1 import socket 2 import time 3 4 5 def socket_bind(server_socket, host, port=514, max_retries=5): 6 retries = 0 7 while retries < max_retries: 8 try: 9 server_socket.bind((host, port)) 10 print(f"syslog服务器已启动,监听端口{port}") 11 break # 如果绑定成功,跳出循环 12 except OSError: 13 port = input(f"当前端口 {port} 可能被占用,请重新输入一个端口(500-65500):") 14 while True: 15 if not port.isdigit(): 16 port = input("输入无效,不是一个有效的整数,请重新输入:") 17 continue 18 port = int(port) 19 if not 500 <= port <= 65500: 20 port = input("输入无效,数字不在范围内,请重新输入:") 21 continue 22 break 23 retries += 1 24 else: 25 print("绑定端口失败,即将退出...") 26 time.sleep(3) 27 exit() 28 29 30 def udp_server(host, port): 31 # 创建UDP套接字 32 with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as server_socket: 33 # 将套接字绑定到指定的地址和端口 34 socket_bind(server_socket, host, port) 35 with open("syslog.log", mode="w", encoding="utf-8") as s: 36 while True: 37 # 接收数据 38 data, client_address = server_socket.recvfrom(10000) 39 print(f"接收到来自 {client_address} 的日志: {data.decode('utf-8')}", flush=True) 40 s.write(f"接收到来自 {client_address} 的日志: {data.decode('utf-8')}") 41 s.flush() 42 43 44 if __name__ == "__main__": 45 # 设置服务器的主机和端口 46 server_host = "0.0.0.0" # 监听所有网络接口 47 server_port = 514 48 49 # 启动UDP服务器 50 udp_server(server_host, server_port)
标签:retries,socket,端口,syslog,服务器,port,python3 From: https://www.cnblogs.com/xfyydhz/p/17978217