python udp 广播

2023-01-31 05:01:14 python udp 广播

最近有需求写了个udp 广播的工具,百度了半天,发现满地坑,wireshark 抓了半天包,发现都是只能localhost收发。这里就记录一下吧

listener.py

#!/usr/bin/env python 
# -*- coding:UTF-8 -*-

from Socket import *
from time import ctime

HOST = '127.0.0.1'
PORT = 21567
BUFSIZE = 1024

ADDR = (HOST,PORT)

udpSerSock = socket(AF_INET, SOCK_DGRAM)
udpSerSock.bind(('',PORT))
print 'wating for message...'
while True:
    data, addr = udpSerSock.recvfrom(BUFSIZE)
    print('...received ->%s  %s'%(addr,data) )


udpSerSock.close()

brocaster.py

from socket import *

HOST = '<broadcast>'
PORT = 21567
BUFSIZE = 1024

ADDR = (HOST, PORT)

udpCliSock = socket(AF_INET, SOCK_DGRAM)
udpCliSock.bind(('', 0))
udpCliSock.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
while True:
    data = raw_input('>')
    if not data:
        break
    print "sending -> %s"%data
    udpCliSock.sendto(data,ADDR)
##    data,ADDR = udpCliSock.recvfrom(BUFSIZE)
##    if not data:
##        break
##    print data

udpCliSock.close()

核心i就是bind和setsockopt  


以后类似的代码就直接找Python的 参考代码吧,为什么手欠用百度。。。。少了谷歌没法活了

Http://svn.python.org/projects/python/trunk/Demo/









相关文章