python socket 广播
python socket udp广播
import socket import time def get_host_ip(): """返回本机IP地址""" try: ss = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) ss.connect(('8.8.8.8', 8070)) ip = ss.getsockname()[0] finally: ss.close() return ip HOST = '<broadcast>' PORT = 9090 BUFSIZE = 1024 ADDR = (HOST, PORT) udpCliSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) #没有bind也能发 udpCliSock.bind(('', 0)) udpCliSock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) count=10 while count>=0: count-=1 data='SSTOP&tuling' udpCliSock.sendto(data,ADDR) print "sending -> %s"%data #如果发往同一局域网安卓端,安卓接收udp广播时可能有问题,但是可以定向udp发给安卓,一般安卓可以广播。过程有些绕,但是应该能用
#安卓广播自己的IP地址,pc收到安卓地址后定向发udp给安卓
#andriod_ip='192.168.0.99'#省略接收udp过程 #udpCliSock.sendto(data,(andriod_ip,PORT)) time.sleep(1) udpCliSock.close() exit(0)
Python socket 监听udp广播
1 2 3 4 5 6 7 | import socket<br> import time<br> #初始化udp s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) s.setsockopt(socket.SOL_SOCKET,socket.SO_BROADCAST, 1 )<br><br> #设置端口可以复用 s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR, 1 ) s.bind(('',udpPort)) <br>count = 10 while count> = 0 :<br> count - = 1 <br> data,addr = s.recvfrom( 1024 )<br> time.sleep( 1 )<br>s.close()<br>exit( 0 ) |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步