python udp 广播

发布时间:2019-09-07 08:08:10编辑:auto阅读(1508)

    最近有需求写了个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/









关键字