# -*- coding: cp936 -*-
"""
UDP使用方法:
1.创建socket
2.发送或接收数据,它不需要connect
"""
import socket,sys,struct,time
host = "time.nist.gov"
port = 37
host = socket.gethostbyname(host)
# 1.使用SOCK_DGRAM,而不是SOCK_STREAM
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
# 3.使用sendto发送数据
s.sendto("",(host,port))
# 2.不使用connect方法
# 4.使用recvfrom接收数据
buf = s.recvfrom(2048)[0]
if len(buf) != 4:
print "wrong-sized reply %d:%s" % (len(buf),buf)
sys.exit(1)
secs = struct.unpack("!I",buf)[0]
secs -= 2208988800
print time.ctime(int(secs))
|