作者:ani_di 
版权所有,转载务必保留此链接 http://blog.csdn.net/ani_di

Lua获取网络时间

网络授时服务是一些网络上的时间服务器提供的时间,一般用于本地时钟同步。 授时服务有很多种,一般我们选择RFC-868。这个协议的工作流程是:(S代表Server,C代表Client)

  1. S: 检测端口37
  2. U: 连接到端口37
  3. S: 以32位二进制数发送时间
  4. U: 接收时间
  5. U: 关闭连接
  6. S: 关闭连接

协议非常简单,用TCP连接上后,服务器直接把时间发送回来。发送的是从1900年1月1日午夜到现在的秒数。

使用luasocket

实现的方案有很多种,Lua不一定是最简单的,选择只是出于个人兴趣。直接上代码吧

-----------------------------------------------------------------------------
-- Network Time Protocal
-- Author: ani_di
-----------------------------------------------------------------------------
package.cpath = package.cpath .. ';D:\\tools\\Lua\\5.1\\clibs\\?.dll;?.dll'
local socket = require "socket.core" server_ip = {
-- "129.6.15.29",
"132.163.4.101",
"132.163.4.102",
"132.163.4.103",
"128.138.140.44",
"192.43.244.18",
"131.107.1.10",
"66.243.43.21",
"216.200.93.8",
"208.184.49.9",
"207.126.98.204",
"207.200.81.113",
"205.188.185.33"} function nstol(str)
assert(str and #str == 4)
local t = {str:byte(1,-1)}
local n = 0
for k = 1, #t do
n= n*256 + t[k]
end
return n
end -- get time from a ip address, use tcp protocl
function gettime(ip)
print('connect ', ip)
local tcp = socket.tcp()
tcp:settimeout(10)
tcp:connect(ip, 37)
success, time = pcall(nstol, tcp:receive(4))
tcp:close()
return success and time or nil
end function nettime()
for _, ip in pairs(server_ip) do
time = gettime(ip)
if time then
return time
end
end
end

代码原理不细说,非常简单。唯一值得一提的是socket库包含。最开始用的这句 require "socket"

在解释器中表现很好,但在用C中调用会找不到相应的module。错误提示

    no field package.preload['socket']
no file '.\socket.lua'
no file 'F:\Projects\Lua\nettime\lua\socket.lua'
no file 'F:\Projects\Lua\nettime\lua\socket\init.lua'
no file 'F:\Projects\Lua\nettime\socket.lua'
no file 'F:\Projects\Lua\nettime\socket\init.lua'
no file 'D:\tools\Lua\5.1\lua\socket.luac'
no file '.\socket.dll'
no file '.\socket51.dll'
no file 'F:\Projects\Lua\nettime\socket.dll'
no file 'F:\Projects\Lua\nettime\socket51.dll'
no file 'F:\Projects\Lua\nettime\clibs\socket.dll'
no file 'F:\Projects\Lua\nettime\clibs\socket51.dll'
no file 'F:\Projects\Lua\nettime\loadall.dll'
no file 'F:\Projects\Lua\nettime\clibs\loadall.dll'.

网上也有好多类似的提问,大抵是没仔细看作者的Guide。显著的有这么一句

The other two environment variables instruct the compatibility module to look for dynamic libraries and extension modules in the appropriate directories and with the appropriate filename extensions.>

LUAPATH=/?.lua;?.lua LUACPATH=/?.dll;?.dll

至于"socket.core",windows默认安装位于“\socket\core.dll”。

C宿主调用

#include <stdio.h>
#include <string.h>
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
#include <time.h>
#include <Windows.h> int load(lua_State* L, const char* func, unsigned int* utc) {
lua_getglobal(L, func);
if (lua_pcall(L, 0, 1, 0)) {
printf("Error Msg pcall %s.\n", lua_tostring(L, -1));
return -1;
} if (!lua_isnumber(L,-1)) {
printf("time should be a number\n" );
return -2;
} *utc = lua_tonumber(L,-1);
lua_pop(L, -1);
return 0;
} void TimetToFileTime( time_t t, LPFILETIME pft )
{
LONGLONG ll = Int32x32To64(t, 10000000) + 116444736000000000;
pft->dwLowDateTime = (DWORD) ll;
pft->dwHighDateTime = ll >>32;
} int main()
{
lua_State* L = luaL_newstate();
unsigned int utc = 0;
luaL_openlibs(L);
if (luaL_loadfile(L, "nettime.lua") || lua_pcall(L, 0, 0, 0)) {
printf("Error Msg load %s.\n", lua_tostring(L, -1));
return -1;
}
do {
if(load(L,"nettime", &utc) == 0) {
time_t tt = utc - 2208988800L;
SYSTEMTIME st;
FILETIME ft;
TimetToFileTime(tt, &ft);
if (FileTimeToSystemTime(&ft, &st))
{
printf("Today is: %d-%d-%d\n", st.wYear, st.wMonth, st.wDay);
SetSystemTime(&st);
}
break;
} else {
puts("No network!");
Sleep(10000);
}
} while (1);
lua_close(L);
return 0;
}

Lua获取网络时间的更多相关文章

  1. python获取网络时间和本地时间

    今天我们来看一下如何用python获取网络时间和本地时间,直接上代码吧,代码中都有注释. python获取网络时间 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 ...

  2. QT+VS2013 * 获取网络时间

    使用qt函数获取网络时间 现在Qt Project Setting中的Qt Modules勾选NetWork,再导入头文件我也忘了叫什么了 QStringList net_time; QTcpSock ...

  3. Unity通过NTP获取网络时间

    最初通过qq时间服务器获得时间,经常出现有网络也获取失败的情况. 后面寻找解决办法,查找资料终于发现通过ntp时间服务器获取网络时间的方法.   首先游戏开始获得初始化网络时间,通常只获取一次,其他时 ...

  4. ESP8266- 使用AT指令获取网络时间

    前言:很早就考虑过用 ESP8266 获取网络时间,以前都是用 ESP8266 刷机智云的 Gagent 固件,但无奈现在手头的 ESP-01 的 Flash 只有 1M,实在无法胜任.经过在网络上的 ...

  5. iOS获取网络时间与转换格式

      [NSDate date]可以获取系统时间,但是会造成一个问题,用户可以自己修改手机系统时间,所以有时候需要用网络时间而不用系统时间.获取网络标准时间的方法: 1.先在需要的地方实现下面的代码,创 ...

  6. Android获取网络时间的方法

    一.通过免费或者收费的API接口获取 1.免费 QQ:http://cgi.im.qq.com/cgi-bin/cgi_svrtime 淘宝:http://api.m.taobao.com/rest/ ...

  7. c#获取网络时间并同步本地时间

    通过TCP形式来获取NTP时间.主要代码如下: [DllImport("kernel32.dll")] private static extern bool SetLocalTim ...

  8. vc 获取网络时间

    方式1 : #include <WinSock2.h> #include <Windows.h> #pragma comment(lib, "WS2_32" ...

  9. Lua获取当前时间

    更多好的文章就在 blog.haoitsoft.com,请大家多多支持! local getTime = os.date(“%c”); 其中的%c可以是以下的一种:(注意大小写) %a abbrevi ...

随机推荐

  1. Hibernate 3中如何获得库表所有字段的名称

    15问:Hibernate 3中如何获得库表所有字段的名称 答:可以使用以下的程序获得. Configuration conf = new Configuration(); conf.configur ...

  2. 黑龙江省第七届大学生程序设计竞赛-Heap

    描述 A heap is a full binary tree; for each node, its key is greater than its two sub-node’s key. Two ...

  3. ZJOI2013 防守战线

    题目 战线可以看作一个长度为\(n\)的序列,现在需要在这个序列上建塔来防守敌兵,在序列第\(i\)号位置上建一座塔有\(C_i\)的花费,且一个位置可以建任意多的塔,费用累加计算.有\(m\)个区间 ...

  4. 11gOCP 1z0-052 :2013-09-11 MGR_ROLE role........................................................A66

    转载请注明出处:http://blog.csdn.net/guoyjoe/article/details/11584537 正确答案A 实验测试 1.创建用户:SKD gyj@OCM> crea ...

  5. Python 对Twitter中指定话题的被转载Tweet数量的频谱分析

    CODE: #!/usr/bin/python # -*- coding: utf-8 -*- ''' Created on 2014-7-10 @author: guaguastd @name: r ...

  6. iPhone5C三大看点:性能不输iPhone5 或售3399元

    乐杨俊编辑修改转载: iPhone 5C的发售时间或最早在9月18日,抢在中秋节前:最迟至国庆十一假期期间. [IT商业新闻网综合讯](记者 林涛)苹果2013年秋季发布会还有几个小时即将开幕,除了i ...

  7. C#利用Lambda和Expression实现数据的动态绑定

    在程序开发过程中,有时为了让数据能够实时更新,我们会采用数据绑定来实现. 一般我们数据绑定时我们是这样写的 public class Helper : INotifyPropertyChanged { ...

  8. webstorm与phpstorm主题配置

    原创. 更换webstorm的主题的,照着网上的教程试了好多次都发现不行,而且我之前有个同学也是这样的问题,找不到相关的colors文件夹,所以在网上教程的基础上对于更改主题做了细微的修改. 1.下载 ...

  9. 8天玩转并行开发——第二天 Task的使用

    原文 8天玩转并行开发——第二天 Task的使用 在我们了解Task之前,如果我们要使用多核的功能可能就会自己来开线程,然而这种线程模型在.net 4.0之后被一种称为基于 “任务的编程模型”所冲击, ...

  10. .net面试题大全(有答案)

    在网上找来的,希望对大家有所帮助.     1 (1)面向对象的语言具有__继承性_性._封装性_性._多态性 性. (2)能用foreach遍历访问的对象需要实现 _ IEnumerable 接口或 ...