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)

 

posted @   dyan1024  阅读(2936)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示