udp server

#!/usr/bin/env python
import socket,traceback,time,struct

host = ""
port = 1234
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1)
s.bind((host,port))

while 1:
	try:
		msg,add = s.recvfrom(8192)
		secs = int(time.time())
		secs -=60*60*24
		secs += 2208988800
		reply = struct.pack("!I",secs)
		s.sendto(reply,add)
	except (KeyboardInterrupt,SystemExit):
		raise
	except:
		traceback.print_exc()



#!/usr/bin/env python
import socket
import sys
import struct
import time

hostname = '127.0.0.1'

port = 1234


host = socket.gethostbyname(hostname)

s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s.sendto('',(host,port))

print "Looking for replies"
buf = s.recvfrom(2048)[0]
if len(buf) !=4:
    print "Wrong sized replay %d:%s" %(len(buf),buf)
    sys.exit(1)    
secs = struct.unpack("!I",buf)[0]
secs -= 2208988800
print time.ctime(int(secs))

你可能感兴趣的:(socket,python)