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广播
import socket
import time
#初始化udp s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) s.setsockopt(socket.SOL_SOCKET,socket.SO_BROADCAST,1)
#设置端口可以复用 s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) s.bind(('',udpPort))
count=10 while count>=0:
count-=1
data,addr=s.recvfrom(1024)
time.sleep(1)
s.close()
exit(0)