C 时间服务器时间类型问题
因此,我正在linux上用C编写一个小的时间服务器客户端应用程序,它应该向客户端发送当前的unix时间戳 它工作得很好,但我被告知时间可能并不总是相同的大小和字节顺序。我如何确保我发送的时间总是让客户理解 到现在为止,我只是这样做C 时间服务器时间类型问题,c,linux,sockets,networking,time-t,C,Linux,Sockets,Networking,Time T,因此,我正在linux上用C编写一个小的时间服务器客户端应用程序,它应该向客户端发送当前的unix时间戳 它工作得很好,但我被告知时间可能并不总是相同的大小和字节顺序。我如何确保我发送的时间总是让客户理解 到现在为止,我只是这样做 time_t now = htonl(time(0)); 然后把它寄出去 我在google和stackoverflow上搜索过,但似乎其他人只发送由ctime()或strftime()生成的时间字符串 提前谢谢 一般来说,发送二进制数据容易出错,因为发送方和接收方对
time_t now = htonl(time(0));
然后把它寄出去
我在google和stackoverflow上搜索过,但似乎其他人只发送由ctime()或strftime()生成的时间字符串
提前谢谢 一般来说,发送二进制数据容易出错,因为发送方和接收方对二进制数据的解释方式可能不同 特别是对于
time\u t
来说,甚至不清楚会涉及多少位,它可能是32位或64位,甚至更复杂,因为time\u t
甚至可能实现为struct
在使用的特殊情况下,假定为32位,因为htonl()
采用32位值
因此,故障安全解决方案实际上是发送系统时间的文本表示
从编程角度看,这可能如下所示:
char st[64] = "";
{
struct * tm = gmtime(time(NULL));
if (NULL == tm)
{
fprintf(stderr, "gmtime() failed\n");
}
{
if(0 == strftime(st, sizeof(st), "%s", tm)) /* Prints the text representaiotn of the seconds since Epoch into st. */
{
fprintf(stderr, "strftime() failed\n");
}
}
}
要反转此操作,可以使用strtime()
:
使用strtime()
和strftime()
的好处是,只要在调用这两个函数时修改指定的格式,就可以轻松更改传输中日期/时间的格式
将%s“
更改为%Y-%m-%d%H:%m:%s”
会像“2014-05-20 13:14:15”
那样传输时间
但是,如果您真的想以二进制格式发送Epoch后的秒数,并保持故障安全性和可移植性,则需要注意三件事:
#include <time.h>
#include <inttypes.h> /* For uint64_t, as 64bit should do to represent the seconds since Epoch for the next few years. */
...
time_t t_epochbegin;
memset(&t_epochbegin, 0, sizeof(t_epochbegin);
uint64_t t_host = (uint64_t) difftime(time(NULL), t_epochbegin); /* Get the seconds since Epoch without relying on time_t being an integer. */
uint64_t t_network = htonll(t_host); /* Convert to network byte order. */
#包括
#对于uint64_t,应包括/*位,因为64位应表示未来几年自历元起的秒数*/
...
时代开始了;
memset&t_epochbegin,0,sizeof(t_epochbegin);
uint64_t_host=(uint64_t)difftime(time(NULL),t_epochbegin)/*获取自Epoch以来的秒数,而不依赖于time是整数*/
uint64_t_network=htonll(t_主机);/*转换为网络字节顺序*/
关于如何实施非标准的htonll()
请参见此问题的各种答案:
以上示例中的所有代码都假设代码运行的系统提供了计时器,尽管调用
time()
不会失败。非常感谢!这比我要求的要多,如果可以,我现在就投票给你!)
#include <time.h>
#include <inttypes.h> /* For uint64_t, as 64bit should do to represent the seconds since Epoch for the next few years. */
...
time_t t_epochbegin;
memset(&t_epochbegin, 0, sizeof(t_epochbegin);
uint64_t t_host = (uint64_t) difftime(time(NULL), t_epochbegin); /* Get the seconds since Epoch without relying on time_t being an integer. */
uint64_t t_network = htonll(t_host); /* Convert to network byte order. */