Python网络编程基础笔记-套接字广播

1.LAN广播服务器
               
               
                # -*- coding: cp936 -*-
"""
广播服务器,接收来自广播的消息,并进行应答
设置socket选项:SO_BROADCAST
"""
import socket
host = ""
port = 50000
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
s.setsockopt(socket.SOL_SOCKET,socket.SO_BROADCAST,1)
s.bind((host,port))
while 1:
    message,address = s.recvfrom(8192)
    print "Got data from",address
    s.sendto("I am here",address)
   
2.广播客户端
# -*- coding: cp936 -*-
"""
对socket进行广播,使用地址,LAN中的所有机器会收到此消息
此客户端收到应答消息后退出.
"""
import socket,sys
dest = ("",50000)
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET,socket.SO_BROADCAST,1)
s.sendto("Hello",dest)
while 1:
    (buf,address) = s.recvfrom(2048)
    if not len(buf):
        break
    print "received from %s:%s" % (address,buf)