连接NTP服务器,获取网络时间,请赐教
SET CENTURY onSET DATE ANSI
SET HOURS TO 24
CLEAR
?1
fh=_GetNetTime("128.138.140.44",13) &&这个成功,以下均失败,不知道为什么
?zh(fh)
?2
fh=_GetNetTime("s1a.time.,123)
?zh(fh)
?"2-1"
fh=_GetNetTime("114.118.7.163",123)
?zh(fh)
?"2-2"
fh=_GetNetTime("ntp.ntsc.,123)
?zh(fh)
?"3-1"
fh=_GetNetTime("139.199.215.251",123)
?zh(fh)
?"3-2"
fh=_GetNetTime("ntp.,123)
?zh(fh)
retu
FUNCTION _GetNetTime(szNtpIP, ddNtpPort)
LOCAL stWsaData, stSockAddr, szBuffer, dhSocket
LOCAL i, ddLen,ret
DECLARE LONG WSAStartup IN "Ws2_32" LONG, STRING@
DECLARE LONG WSACleanup IN "Ws2_32"
DECLARE LONG socket IN "Ws2_32" LONG, LONG, LONG
DECLARE LONG connect IN "Ws2_32" LONG, STRING@, LONG
DECLARE LONG recv IN "Ws2_32" LONG, STRING@, LONG, LONG
DECLARE LONG closesocket IN "Ws2_32" LONG
DECLARE LONG inet_addr IN "Ws2_32" STRING@
DECLARE LONG htons IN "Ws2_32" LONG
DECLARE INTEGER gethostbyname in WSOCK32 String
DECLARE LONG inet_ntoa IN "Ws2_32" LONG
stWsaData = REPLICATE(0h00, 398)
szBuffer = REPLICATE(0h00, 256)
stSockAddr = REPLICATE(0h00, 16)
WSAStartup(0x202, @stWsaData)
dhSocket = socket(2, 1, 6)
IF ISDIGIT(szNtpIP)
stSockAddr = 0h0200;
+ BINTOC(htons(ddNtpPort), "2RS");
+ BINTOC(inet_addr(@szNtpIP), "4RS");
+ REPLICATE(0h00, 8)
else
RET = CTOBIN(SYS(2600, gethostbyname(@szNtpIP) + 12, 4), "4RS") &&偏移12,IP地址列表
RET = CTOBIN(SYS(2600, RET, 4), "4RS") &&IP地址
stSockAddr = 0h0200;
+ BINTOC(htons(ddNtpPort), "2RS");
+ SYS(2600, RET, 4);
+ REPLICATE(0h00, 8)
endif
ddLen = 0
IF connect(dhSocket, @stSockAddr, LEN(stSockAddr)) != -1
FOR i = 1 TO 9
ddLen = recv(dhSocket, @szBuffer, LEN(szBuffer), 0)
IF ddLen != -1
EXIT
ENDIF
ENDFOR
ENDIF
closesocket(dhSocket)
WSACleanup()
IF ddLen > 0
szBuffer = LEFT(szBuffer, ddLen)
RETURN szBuffer
ELSE
* MESSAGEBOX("网络异常,时间同步失败")
RETURN ""
ENDIF
ENDFUNC
PROCEDURE zh
LPARAMETERS szutc
IF EMPTY(szutc)
else
ddYear = INT(VAL(SUBSTR(szUTC, 8, 2))) + 2000
ddMonth = INT(VAL(SUBSTR(szUTC, 11, 2)))
ddDay = INT(VAL(SUBSTR(szUTC, 14, 2)))
ddHour = INT(VAL(SUBSTR(szUTC, 17, 2)))
ddMinute = INT(VAL(SUBSTR(szUTC, 20, 2)))
ddSecond = INT(VAL(SUBSTR(szUTC, 23, 2)))
RETURN DATETIME(ddYear,ddMonth,ddDay,ddHour,ddMinute,ddSecond)+8*3600
endif
RETURN ""