#!/usr/bin/env python3 # -*- coding: utf-8 -*- import socket import netifaces import signal import sys import time
defsend_broadcast_message(sock): # 获取树莓派的IP地址 interfaces = netifaces.interfaces() for iface in interfaces: addrs = netifaces.ifaddresses(iface) if netifaces.AF_INET in addrs: ip = addrs[netifaces.AF_INET][0]['addr'] if ip.find('127.0.0.1') >= 0: continue
# 发送UDP广播消息 broadcast_ip = '255.255.255.255'# 广播地址 port = 7893# 自定义端口号
message = "Raspberry IP address is {}".format(ip)
try: sock.sendto(message.encode(), (broadcast_ip, port)) except socket.error as e: print("Failed to send broadcast message:", str(e))
defsigterm_handler(signal, frame): # 执行清理操作,例如关闭套接字等 if sock: sock.close() sys.exit(0)