1 #!/usr/bin/python 2 #coding=utf-8 3 #广播端 4 import sys,socket 5 import time 6 7 s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) #创建数据报套接字 8 s.setsockopt(socket.SOL_SOCKET,socket.SO_BROADCAST,1) #设置套接字选项可以发送广播 9 dest=('broadcast',5455) #广播地址默认的.255 10 #不用绑定,不用监听,不用accept 11 print "waiting for ..." 12 while 1: 13 time.sleep(1) 14 s.sendto("hello",dest) #发送 15 buf,addr=s.recvfrom(1024) #接收 16 if not len(buf):break 17 print "REcv from:",addr #打印
1 #!/usr/bin/python 2 #coding=utf-8 3 #接收端 4 import socket,traceback 5 6 HOST = '' 7 PORT = 9999 8 9 s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) 10 s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) 11 s.setsockopt(socket.SOL_SOCKET,socket.SO_BROADCAST,1) 12 s.bind((HOST,PORT)) 13 14 while True: 15 try: 16 message,address = s.recvfrom(4096) 17 print "Got data from",address 18 s.sendto("I am here",address) 19 except (KeyboardInterrupt,SystemExit): 20 raise 21 except: 22 traceback.print_exc()